Stopping a Thread.... again

Hi all,
a couple of months ago I've posted a similar topic, on how to stop a thread without using the deprecated stop() method. Still, no result. I have a great deal of calculations that should be done in a separate thread. Due to the fact that the calculations might take up to 10 secons (or more), I would like to give the ability to the user to stop the process of calculations.
public class Calculations(){
    //Field Declaration
      Thread t;
    public void doTheJob(){
        if(t != null)
             t = null;
        t  = new Thread( new Runnable(){ public void run(){
            <PERFORM THE CALCULATIONS>
        t.start();
    public void stopTheJob(){
             <HOW????, t.stop() works "fine">
}The stop() method of class Thread will do perfectly and stop the procedure. However is deprecated. I've checked the alternative of stop using while( t!= null) loops, but there is no loop in the procedure!! There is just a bunch of operations that should be done in a separate thread. It is logical that something as the following won't do if the procedure has already started.
    public void stopTheJob(){
             if( t != null)
                  t = null; //No point if the procedure has already started
    }Please correct me if I'm wrong, but help me understand how...
I am not a programmer and not that smart but I still want to solve this issue.
I would gladly provide more information if necessary.
Thnx in advance,
F.

There are fundamental problems with monitors (i.e. synchronized bits). You can be sure they've given a lot of thought to cleaning up and decided there's no safe way to do it.
stop still works and there are very rare situations in which I'd use it. In particular if the thread were running someone else's not fully trusted code and a framework decided an infinite loop was happening. Depracation is a warning, not an error.
However it's generally no problem at all to have a thread watch for being interrupted and stop itself.
Generally the interrupt call is the best mechanism since it kicks the thread out of wait or sleep, or sets a flag which you can test (or which will cause an exception next time you wait or sleep.

Similar Messages

  • Stopping a thread from running

    Hai
         I am new to java. It would be helpful for me if someone helps me out in doing this.
         Actually in my program ,I should
    i. Find out whether a particular file exists in the given directory or not.
    ii. If the file doesn't exist, my program should wait for certain timeframe and check for the same file again.
    iii. If the program cannot find the required file within the timeout specified, my application should exit.
         I have done (i) and (ii) using threads. But in the case of (iii), I came to know that stop() method is depricated.
         I am providing my code for a better understanding. Could you please let me know, what would be the best way to stop the thread from running after the timeout is reached in my program?
    Thanx in advance
    import java.io.File;
    public class Fileexists implements Runnable
    static Thread t;
    public static void main(String[] args)
         System.out.println("creation of object");     
         FileExists test = new FileExists();
         t = new Thread(test);
         t.start();
    // run method
    public void run()
         File f = new File("searchfile.txt");
         boolean b = f.exists();
    System.out.println();
    if(b == false)
    System.out.println("Required file doesnot exists");
    try
         t.sleep(20000);
    catch (InterruptedException e)
         // TODO Auto-generated catch block
         e.printStackTrace();
              t.run();
    else
    System.out.println("Required file found");
    } // end of run()
    } // end of FileExists class

    Actually your use of threads is a difference which makes no difference. The JVM starts an initial thread and runs your main(), at the end of which you start a thread and return. So you've just replaced one thread with another. There's no parallel processing.
    The t.run() at the end of your run() method won't work. A particular Thread object can only run once. It will give you an IllegalStateException.
    I can't see how multi-threading will help you with this task at all, all you need is a simple loop with a Thread.sleep in it.
    If you really want to use a separate thread or Timer to implement a timeout (as an exercise) then use Thread.interrupt() to wind up a thread. The looping thread should test with Thread.interrupted() in it's loop condition, if it's in sleep() when interrupted an InterruptedException will be thrown which you should catch and allow to break the loop and let the thread terminate.
    So your loop structure looks like:
    try {
    while(!Thread.interrupted()) {
        ...  do your test
        Thread.sleep(.....);
      System.out.println("Thread terminated by detecting interrupted");
      } catch(InterruptedException ex)  {
         System.out.println("Thread interrupted from sleep");
    You can get the Thread for the main thread simply by storing Thread.currentThread() in a Thread reference.
    I'd suggest using a java.util.Timer to launch your time-out and leave the loop on the main thread started by the JVM.

  • Stopping a Thread when downloading

    Hi everyone!
    I'm develop a app to connect to a FTP Server and dowload and upload files. When I click on Cancel button, the app will still running but the download will stop.
    So, my problem is: How can I stop a Thread when i'm donwloading a file?
    I'm using Commons Net 3.0.1 to connect from a FTP. I have tried logout(), disconnect(), abort()... Into Threads I have tried interrupt(), yield(), stop(), destroy()... But not works!
    The "safe way to stop a Thread" don't work for me, becouse I'm not using a While but yes this line code to download the file:
    ftp.retrieveFile(TARGET, SOURCE);
    When I click on cancel button the donwload still running in background.
    PS: Sorry for my english :)

    Problem solved! Using the method retrieveFileStream() and the famous "the safe way to stop a Thread" I can stop it without need to close my app!
    The code was (adapted):
    OutputStream os;
    InputStream is;
    localDownload = new FileOutputStream(new File(LOCAL, NOME_ARQUIVO));
    os = localDownload;
    is = ftp.retrieveFileStream(LOCAL_FTP+NOME_ARQUIVO_FTP);
    if(is != null){
         int bytesRead = -1;
         final byte[] buffer = new byte[4096];
         while ((bytesRead = is.read(buffer)) != -1){
              if(cancelado == false)
                   os.write(buffer, 0, bytesRead);
              else
                   cancelado = false;
    is.close();
    ftp.completePendingCommand();PS: The method completePendingCommand() is fundamental for the download can be stoped.
    Again: sorry for my english :)
    Edited by: 866587 on 17/06/2011 09:53

  • Spring is in the air, and right on cue my Verizon DSL stops working. AGAIN

    Some background. I have Verizon DSL service, with a phone line dedicated to its use. The phone line is used for nothing else, and has the required filters attached.
    Two years ago, when spring arrived, we began have trouble with out internet connection. Our modem would get a red light on the Internet connection. This would happen every day between 10am and noon, and would last from minutes to hours. I spent hours on the phone with Tech support. They reduced speed, which was unnacceptable and did not work. They sent a tech to our home twice that summer to replace lines inside the house, replace line outside the house, make adjustments at  the central office and the local "hub". Nothing worked. Fall came, the issues stopped, and everything worked fine thoughtout the winter.
    Last year, spring arived, we began to have trouble with out internet connection. Same thing as the previous year. Called tech support. Told them that I had done this song and dance the previous year. I would not start from the beginning with every single call, I would not turn off/on the modem, give model numbers, check direct lines from computer to modem. I had done it all the previous year. I thought surely there was some kind of record for my account that could be accessed. To no avail. I spent countless hours and days on the phone with tech support. I spoke with techs, supervisors, managers, talked, yelled, got nowhere. They sent a new modem. Nothing changed. They sent the same tech to my home as the previous year. He still didn't know what the problem was. Changed the phone jack. Changed a different line outside. Still didn't work.
    I came on here and left a lenghthy message voicing my frustration. I was told that someone from the US tech support office would contact me (Executive Appeals). The representative from there was very helpful. He explained what each of the lights on the modem did and what blinking/not blinking/ off/red actually meant. He had them change the modem at the central office. Problem solved, I thought. We had out normal running speed of 3360/863 again. No more internet cutting out daily. But, it was fall. Apparently, this would have happened anyway. Because...
    This year, spring arrived, and we are having trouble with our internet connection. We have any and all combinations appearing on the modem. The internet cuts out at all times of the day and night. It stays off for minutes to hours. Internet flashes, turns red, goes out. DSL and DATA blink, stay on, alternate blinking speeds. Sometimes the phone line has static, other times it doesn't. There is no pattern to anything.
    I have not called normal tech support. The people in India are clueless, have never come close to solving the issue, and I will not waste my time and cell phone minutes talking to them. I saved the phone number and all information for the US representative I spoke with last year. I have left 2 messages for him over the past week. He will not return my call. Our internet speed had gone from 3360kbps/863kbps, to 2928kbps/860kbps, to 2560kbps/860kbps, to 2112kbps/860kbps over the course of the last week, as shown on the verizon modem page. This is what they do every year, and it in UNACCEPTABLE. Slowing the speed accomplishes nothing, since we still have the same problems. All that changes is we have DSL service that runs a little faster than dial-up.
    If anyone out there has a suggestion as to what I can do to fix these issues after 3 years, please let me know. Apparently no one at Verizon knows how to address the problem.

    Verizon Reps,
    I have not been to my private message thread "Spring is in the air, and right on cue my Verizon DSL stops working. AGAIN"  since the beginning of June. The problems I was experiencing have not been fixed, but I was not posting because nothing was happening for a while. My Verizon Appeals rep was trying to figure out what to do.
    She has since had 2 techs come to the house. The second one just recently. He changed something in the box a few blocks away. This not only didn't fix it, but has made the issue more prevelent than it was before. I would like to record all of our outages and lost connections, but the thread appears "closed".
    At this point, I'm not sure it matters. The rep all but said that she has no idea what to do to fix it, or if it can be fixed. Fresh out of ideas, I guess. But I'd still like to keep track, since we have been without internet more than with for the last few days.
    Thanks,
    Theresa

  • Start/Stop a thread dynamically.

    i have an attribute Thread t;
    i initialize it as
    t = new Thread(){
         public void run(){
              try{
                   System.out.println("do something");
                   sleep(10000);  // sleep a while
              catch(Exeception e){}
    };i invoke it by t.start(); and stop it by t.sopt(), but i failed in t.start() to start it again
    How could i start and stop it externally without re-new the object ?

    The stop() method should not be used.
    Instead you might want to try the pattern:
    volatile Thread aThread=null;
    public void run() {
    aThread = this.currentThread();
    while(aThread!=null) {
    //sleep
    and write a method to set aThread to null to stop the thread.

  • Stop current thread

    I have got a Thread (made from swing thread).
    In the run() method i create a frame with a button that has an "actionperformed" and I show this frame and I put a loop like "
    while(true){
    Thread.currentTread.sleep(1000);
    System.out.println("bip");
    But in the button action I try to kill this Thread.
    But, no one of the methods from Thread class "yield", "destroy", "interrupt" seems to work.
    QUESTION :
    ==> How can I do to kill a Thread when I have his name or when it is the current Thread.

    Right - your best option is to either make the thread null (thus removing the object and stopping the thread from running), which is a bit heavy handed. Be careful of this, especially if you'll be creating new instances all the time - creating and scheduling threads can be quite processor and time intensive.
    The other option is to have the while loop use a boolean variable, such that you can do something like
    // instnace variable:
    private boolean running = true;
    // now a method to modify it:
    public void setRunning(boolean run)
      running = run;
    //some more code in your class...
    // now the body of the run method:
    while(running)
      Thread.currentTread.sleep(1000);
      System.out.println("bip");
    }Thus, when someone calls yourObjectName.setRunning(false), the run() method will quit.
    All you have to do now is call yourObjectName.start() to make it run again.
    I can't think of any cleaner ways to do this, so if they're any Java Gurus out there, help me out here.
    So, do this if you want to stop a thread running; but if you really want to kill it, and not use it again, make the object null.
    Let me know if this works for you,
    Rich

  • How to stop the thread?

    Hi,
    How to stop the thread in java. This is my program.
    import java.net.InetAddress;
    public class ThreadPing extends Thread {
         ThreadPing(String pingIP)
              super(pingIP);
              start();
         public void run()
              try
              String pingIP = Thread.currentThread().getName();
              InetAddress inet = InetAddress.getByName(pingIP);
              Boolean get=inet.isReachable(1500);          
              if(get==true)
                   System.out.println(inet.getHostName());               
              }catch(Exception e)
         public static void main(String args[])
              for(int i=1;i<=100;i++)
                   String pingIP = "192.168.1."+i;
                   ThreadPing tp = new ThreadPing(pingIP);
    Thanks in advance.

    The simplest way to stop all the thread is to make all thread daemons and exit the program when you want them to stop.

  • How to stop main thread ?

    Hi,
    Inside my java class, after I launch a GUI, I want to stop this main thread. After user make some choice and close GUI window, then, I want to go back to main thread. I use wait() method inside my class to stop main thread , but it does not work and it give me "IllegalMonitorStateException" error. I met same thing, when user close the GUI window and call method notifyAll(). How to stop main thread for a while and how to go back?? Thanks
    Gary

    Hi,
    you can create a boolean, and create a while loop, with a Thread.sleep(time); when you want to continue, you just have to change the state of your boolean. So you don't hava to exit the main. And you can't restart a run() in a thread. You can run it only once, so try to keep in your run() with an appropriate loop.
    Hope it helps.
    S�bastien

  • Stopping a Thread in Infinite Loop

    I've read several articles on how to stop Threads, and all of them point to using Thread.interrupt(). The problem right now is what happens when the thread is in an infinite loop. For example:
    class A implements Runnable
        public void run()
            while(!Thread.currentThread().isInterrupted())
                  while(true);
    //in other class's main method:
    Thread a = new Thread(new A());
    a.start();
    a.interrupt();The a.interrupt() call only sets the isInterrupted flag in Thread, but it does not terminate the thread as a.stop() would. However, stop() throws a ThreadDeath exception that I would not want to have to deal with. Is there any way to stop this infinite loop thread safely?
    Thanks in advance!

    No need to get snitty. You certainly did not make clear that you are not a newbie at programming. Plenty of newbies who barely have a grasp of the language fundamentals post thread questions here. I thought I did address the question at hand. It seems I misunderstood what you were asking.
    The only way to safely stop that inner loop is like so: while (...) {
       while (!done) {
    }where done is volatile, or all access to it is sychronized on the same lock (meaning you'd sync the !done check above as well).
    If you can't do that, and it's stuck at while (true) and you can't modify the body of the inner loop to check done, then you're SOL.
    (I suppose it's conceivable that 1.6 or 6.0 or whatever it's called will introduce some new safe way to stop that thread, but I haven't heard anything about it.)

  • Has anyone else experienced the stopping and starting again while  playing music in iTunes.  It was fixed but with the last update it has started skipping again.

    Has anyone else experienced the stopping and starting again whil playing music in itunes.  It was working fine wit the prior fix, but after the last update
    it started skipping again. 

    Try it in another vehicle see if it still happens, at least you can narrow it down to your  phone or the car. My 4s play totally fine, I have never had any of those issues. Maybe its time to restore your phone and start over. I would also have someone else play their Iphone in your car, see if it happens to them. Or try yours in someone elses car. Good Luck!

  • How to stop a thread in java 1.5 on windows

    Hi All,
    I am using Java 1.5 on windows plateform. I want to stop all the threads which belongs to a particular process when the timeout occurs. In java 1.5 stop() method is depricated and interrupt method just sets the flag and does not stop the thread actually.
    Is there any way to destroy the thread permenently. I am using TheadPool Executor class.
    Regards
    Rinku Garg

    Hi,
    I am having a timer task which is scheduled to run after some fixed time interval when the process started.
    Now this timer task when started, should destroy the active threads of the request. When the request is timed out then the thread is action should termininate.
    In my case run method of particular thread had already made a call to Database through DAO when the time out occurs. So how can I set up a loop in run method which I found on google.
    thread.stop() is deprecated.
    thread.destroy() is deprecated.
    I used thread.interrupt() but it does not stops the thread.
    Please help me in this scenario.
    Regards
    Rinku Garg

  • Video's and songs start then stop then start again

    Whenever I try to play A Video or A Song, they start, then stop, then start again.
    What should I do?

    Try to uinstall and reinstall your audio device.
    1. On Window vista,Click on Start and type Devive Manager on the search box.Look for sound, video and game controllers.Click on the plus sign,you should see the audio adapter, most toshiba laptops use realtek high definition audio.Just right click and click on uninstall.
    2.After you uninstall,Click action at the top of your device manager and click scan for hardware changes.It should reinstall the audio adapter.
    3. Try to play music.
    Notes: Sometimes the problem is like this because of some driver updates from windows vista.
    -JackBauer

  • Correct way to stop and run again a FPGA reference

    Hi guys !
    I have some issues when I try to stop and run again an FPGA vi, I explain.
    I have two DMA FIFO, one to send data to the FPGA from the CPU, and another from the CPU to the FPGA. When it receives data, the FPGA processes them and sends them back to the CPU and according to the result the CPU makes something. For instance it can be switch on LEDs or rotate a DC motor.
    But to do this kind of actions, I have to use an "FPGA Personality", LEDs and I/O Pins seem to be managed by the FPGA core. So I've to close my FPGA vi reference in charge of receive data from the CPU, make my LEDs switching on and then after rerun again my FPGA VI again, If I don't do that LEDs blinking or motor rotation stay without effect... But close and start again the FPGA VI creates problems during the execution, especially for previous waiting of reading on the DMA FIFO... I've tried to catch errors on the FIFO to start again the FPGA VI with a right timing but nothing... I'm lost and I think that I'm missing something, a concept or something else.
    I can't share my code because I'm working for a company but I would like to know if you have VI with this type of structure : an FPGA reference which have to be halted to allow hardware interaction with the default FPGA personality and then run again, everything with a good synchronisation...
    I hope I'm clear, but if it's not the case, I can reword if necessary.
    Thank you for the help !
    Afghow.
    Solved!
    Go to Solution.

    Afghow wrote:
    I think the end user doesn't have to know that when he wants to make LEDs blinking he has to call a FPGA bitfile. I mean running an FPGA VI and want to make LEDs blink from the CPU VI at the same time should be transparent for the user and this without keep in mind horrors like bitfile switching for instance.
    He doesn't have to load a different FPGA bitfile.  Everything you need that FPGA to do should be in the bitfile.  Keep in mind that we are talking about HARDWARE when we talk about FPGA.  Each time you change bitfiles, the hardware has to be reconfigured.  That takes time and is pointless for the situation you are talking about.  Build your FPGA code to do everything you need it to and you will be fine.
    There are only two ways to tell somebody thanks: Kudos and Marked Solutions
    Unofficial Forum Rules and Guidelines

  • Stopping a Thread Correctly

    Instead of using myThread.stop()
    I should do somthing like this ... correct?
    //In my Thread Dispatcher Class
    private boolean shouldStop = false;
    private Thread myThread;
    public static void setStopThread(boolean b){
    shouldStop = b;
    public boolean stopThread(){
      return shouldStop;
    public void nullifyThread(){
    myThread = null;
    //In my Thread Class
    public void run(){
    while(!myThreadDispatcherInstance.stopThread()){
      //do some Thread Work
    }//end while
    }//end run method
    myThreadDispatcherInstance.nullifyThread();Will the above code handle everything (aside for the setup and initialization part) to override the depreciation of the Thread.stop() method? Or am I missing somthing?
    oh yea also anywhere I'd need to stop the thread i'd put
    ThreadDispatcherClass.setStopThread(true);

    Looks about right, except that you need to declare setStopThead and stopThread synchronized, in order to force writing to and reading from main memory.
    NullifyThread is almost certainly pointless and unneeded.
    stopThread is a rather poor name. It sounds like it's taking an action, rather than returning a value. shouldStop() or idDone() or something would be better.
    Finally regarding "In my Thread class": Rather than extending Thread, you should implement Runnable. You're not really specializing a Thread's behavior, you're just implementing a unit of work for a thread to run.

  • Stopping a Thread (where I don't have control of run)

    Is there any way to stop a thread whose run method simply calls a method of another class?
    For example:
    public class myThread extends Thread
      private String className = ...;
      public void run()
        // get className's "main" method and run it

    Actually...Smarsh is right. This is the correct way
    to stop a thead....stop() is deprecated because it can
    cause a deadlock condition. So, in run(), if you
    defined a boolean like "bStopThread" run would look
    like this:
    public void run()  {
    if(bStopThread)
    return;
    // if we drop here...this is the rest of our run
    un code
    Yeah, I get that's how you should stop a thread...
    Let me rephrase the question a little. Say the thread's run method looks similar to this:
    public void run()
      if (stopped)
        return;
      someOtherClass.aMethod();
    }Once it's in aMethod, I have to let it run until it's done, right? There's no other way to stop a thread other than checking a stop condition?

Maybe you are looking for