How do I stop a thread?

I want any way of just stopping it, midline or anything. I've checked the API and done a lot of tests, but everything is depreciated and throws exceptions everywhere. I just want a method that kills the thread.

It's not the sleeping you should be worried about. It's everything else it does.
The thread may spend most of its time asleep but that's not really the point. This isn't a game of darts where a big sleep target makes you safe. The issue is data integrity. When programming, you should always keep your data (in OOP, that's manifested as object state) logical and consistent, and every modification of that data should move you from one logical and consistent state to another logical and consistent state. Killing a thread in the middle of a transition between two logical and consistent state can leave your data in a state that's neither logical nor consistent.
If your thread spends 99% of it's time asleep, and you just kill it, then most of the time your data will be OK, but that 1% of the time when you kill it at the wrong time, you'll end up with an intermittent bug that'll be a huge pain to find.
If you're worried about the thread hanging around sleeping too long when you want it gone...you can always wake the thread. That's not a problem.

Similar Messages

  • How Can I stop my thread?

    Hi!
    I'm developing an application of computacional geometry. It consist on a JFrame where I put some components like a JToolBar, a JTextArea, etc, and a JPanel. When the JPanel it's painted, there are a button that runs the JPanel in a new Thread.
    The problem is that I have another button to stop the thread, but I can't stop it completely if it is in a I/O operation.
    Here is the code of the run() method:
    public void run()
    Thread thisThread = Thread.currentThread();
    while (kicker == thisThread)
    if (runMode)
    lhull.removeAllElements();
         hull.removeAllElements();
    GrahamScan();
    runMode = false;
    aFrame.doneButton.setEnabled(true);
    stop();
    I stop the thread, but when it's in the GrahamScan() method, it continues painting things in the panel.
    How can I stop the thread completely?
    Thanxs in advance!!

    What's the matter with my line separators and my code indentation?
    Try to use yourThread.interrupt() at your button push event, and this code;
    public void run()
    Thread thisThread = Thread.currentThread();
    try {
    while (kicker == thisThread)
    if (runMode)
    lhull.removeAllElements();
    hull.removeAllElements();
    GrahamScan();
    runMode = false;
    aFrame.doneButton.setEnabled(true);
    stop();
    } catch (InterruptedException iEx){

  • URG & IMP: How does one stop the Thread.currentThread?

    hi,
    I want to stop the current thread.
    Presently teh code used Thread.currentThread.stop()
    However stop() has been deprecated
    Thread.currentThread.interrupt() doesnot seem to help.
    If I try Thread.currentThread.isAlive() post tehinterrupt, it doesnot work as desired and teh thread is still active...
    Any pointers????
    We have alreday tried using the boolean volatile varible to stop the thread as recommended by sun and since this is the currentThread, it cannot be assigned to null.
    Thanks
    Priya

    hi,
    I want to stop the current thread.
    Presently teh code used Thread.currentThread.stop()Whyever would a thread want to deliver a stop() to itself.
    Did you mean that you wanted to stop() a different thread?
    As indicated in the (depreaction) documentation for stop(), using interrupt()
    is a better idea. However, that requires you to have a protocol
    where the receiver of the interrupt then reacts in an appropriate
    manner, i.e. interrupt() can be the basis for cooperative
    thread termination; it can't merely replace a stop() call
    in an existing application without any other changes.
    >
    However stop() has been deprecated
    Thread.currentThread.interrupt() doesnot seem to
    help.
    If I try Thread.currentThread.isAlive() post
    tehinterrupt, it doesnot work as desired and teh
    thread is still active...
    Any pointers????
    We have alreday tried using the boolean volatile
    varible to stop the thread as recommended by sun and
    since this is the currentThread, it cannot be
    assigned to null.Think about what you are trying to achieve. Did you want
    to just do a Throw() out of the current method, with (or
    without )a corresponding Catch() in some outer context)
    so that the you can unwind in case of an exceptional
    condition and have the thread exit?
    >
    Thanks
    Priya

  • How executor handles stopping a thread?

    Hi,
    I am new to concurrency and I have this question:
    I have created a class which implements Runnable
    class MyClass implements Runnable{}I have created an executor (using FixedPool implementation) which I use to start MyClass
    execute(myclass)If I stop myclass from running (i.e. using a stop flag) will the executor remove it from the pool? What will happen if I try to start myclass again? either by just giving myclass.start() or by passing it to the executor.
    any advice will be appreciated!
    Chris

    If I stop myclass from running (i.e. using a stop flag) will the executor remove it from the pool?It isn't in the pool. Threads are in the pool.
    What will happen if I try to start myclass again?Whatever happens in its run() method.
    either by just giving myclass.start()Your class doesn't have a start() method.
    or by passing it to the executor.It will execute.
    If you resubmit the same instance and the stop flag is still set it will do whatever it does under that circumstance.
    None of this has anything to do with the executor's thread pool.

  • In TestStand, how can a stop a Thread.

    Hi,
    I have a main sequence that runs for ever providing the user hasn't pressed the stop button and the Power hasn't failed.
    The Stop button is on a dialogbox in a sequence which is launched in a new thread. The dialogbox is just a MessageBox step type.
    If the Power Supply fails, the loop in the MainSequence is terminated but the execution of the sequence file is not stopped because the DialogBox Sequence is still running and the user will have to press the STOP button to complete the termination of the execution.
    Is there a way to stop the execution of the Dialog sequence from the MainSequence without having to press the STOP button.
    Regards
    Ray Farmer
    Regards
    Ray Farmer
    Attachments:
    StopNewThread.seq ‏38 KB

    Hello Ray,
    There's always a way to do something in TestStand =0) !
    You can use the method "Execution.Terminate" or "Execution.Abort". These methods will terminate (cleanup step groups will execute) or abort (cleanup step groups will NOT execute) ALL the threads belonging to the Execution object. Therefore, after calling this method, your MainSequence AND subsequence will both terminate or abort since they belong to the same execution object.
    If you only want to abort/terminate a particular subsequence, you'll need to launch it in a New Execution instead of in a New Thread. Remember to store the execution reference in a variable because you'll need it when invoking the Execution.Abort or Execution.Terminate methods.
    Note: You can control an
    execution object but not a thread object. In other words, you cannot break, abort nor terminate an individual thread but rather all threads belonging to an execution object.
    Let me know if you have any questions.
    Regards,
    Carlos Leon

  • 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?

  • Stopping a Thread (no control on run method)

    Hi,
    How can we stop a Thread like in the following scenario. If we are in the aMethod() and the stopped variable is set to true by some other thread now how can we return from this run method and stop executing the aMethod(). Any tips are helpful.
    public void run()
    if (stopped)
    return;
    someOtherClass.aMethod();
    Thanks

    I miss the scenario here, where a thread is blocked inside a call to some operating system resource (such as accept() or read() or write()).
    In this case an InterruptedException travels like pacman up the stack, until it's caught, and I think that it should be a scenario in all cases, because it can apply to the blocking call (where it applies already), the predictable loop (try { while() { } } catch (InterruptedException ie) { }), and the one-off algorithm, even though in the latter case, if it's extremely important that we know exactly what we were doing when we were interrupted, it's difficult to avoid either a) many try-catch-blocks, or b) a very good way of examining the stack at the moment of interruption.
    This is, in fact, so important, that I would like to urge Sun to change the API for java.lang.Runnable into
    public interface Runnable {
      public abstract void run() throws InterruptedException;
    }Because, in this way, any thread will always have an endpoint. If you choose to rethrow the exception you still mess up the JVM, of course, like it was, causing it to exit. But at least you must provide yourself with the opportunity to let threads not end, or always die softly.

  • 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

  • Cannot stop this thread...

    Hello, I have the following code:boolean kill = false;
    public void go() {
       while (!kill) {
            sleep(3000);
            //do stuff.
    public void stopThread() {
        kill = true;
    }This code doesn't stop it. I cannot seem to stop this thread with the boolean variable. I think its because I have the thread asleep but I'm not sure. How can you stop a thread that sleeps for a period of time?
    Thanks.

    Here's my code: class CreateGui {
    Vector<Thread> threads = new Vector<Thread>();
    //lots of stuff here...
    public void start() {
         Runnable runner;
    runner = new RunThreads();
         Thread t = new Thread(runner);
         t.setName(_code);
         t.start();
         threads.add(t);
    public void stop() {
         RunThreads r = new RunThreads();     
         r.stopThread();     
    class RunThreads implements Runnable {     
         boolean kill = false; 
    public void run() {
         go();
    public void go() {
       while (!kill) {
         try {
         Thread.sleep(3000); .
         } //try          
         catch (InterruptedException ex) {
         ex.printStackTrace(); }
             //do stuff here...     
              } //while
    } //method go
    public void stopThread() {
         kill = true;
    }The user clicks a button to start a thread, and then clicks another button to stop the thread. With this program I am supposed to have up to 26 threads running at once. I know I may not be doing things totally correctly, but that is what I'm trying to accomplish. I can take the harshest criticism: )

  • How to stop a thread at the end of another

    hello
    I want to run two threads. They start at the same time, and I want one of them to end when the first one finishes.
    I have a main class, a GUI. When I click on a button, it processes an action( first thread), and since this action takes some time, I decided to create a second thread that is a GUI that is a dialog box that says that it is being processed...
    So my dialog bow has to disappear when the process ends.
    I've already tried this:
    boolean stop = false;
    Connect connect = new Connect(this);
    connect.start();
    LdapSearch searching = new LdapSearch();
    searching.start();
    while( connect.isAlive() ){
         if( !connect.isAlive() ){
              stop = true;
    if( stop == true ){
                           searching.interrupt();
    }but unfortunately the text written on my dialog box disappears....
    does anyone knows how I can make a thread stop at the end of another properly?
    thanks for your help!!
    Philippe

    sorry the code i tried is:
    boolean stop = false;
    Connect connect = new Connect(this);
    connect.start();
    LdapSearch searching = new LdapSearch();
    searching.start();
    while( stop == false ){
         if( !connect.isAlive() ){
              stop = true;
    if( stop == true ){
         searching.interrupt();
    }

  • 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

  • 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

  • How to stop a thread in java 5 for a real-time system??

    Hi,
    In Java 5, thread.stop is deprecated. We need to modify some variable to indicate that the target thread should stop running. "The target thread should check this variable regularly........"
    We are currently developing a simple real-time operating system using the basic features of java. It is running on top of SunSPOT (JAVA5). My question is I need to stop a thread in a scheduler loop of a real-time operating system. We cannot check it regularly. Otherwise it is not a real-time operating system.Is there anyway else to do this?
    Thanks,
    Qing

    That's rather hard to answer. You say you are writing in Java, but you're writing an OS. BUt what's executing the Java - you need a VM of some form. Is that a real-time or non-real-time VM? How it does things ultimately controls how effectively you can do what you are trying to do.
    The simple answer is that Thread.stop() is deprecated and that it will not stop a thread in all situations anyway - eg trying to acquire a monitor lock. But all Thread.stop does is make an exception pending on the thread, and as the thread executes it polls to see if there is an exception pending. When this happens depends on the VM: it might be after every bytecode; it might be when the thread transitions states (eg thread-in-java, thread-in-vm, thread-in-native) - it all depends. But it is polling - just the same as checking that variable - it's just implicit in the VM rather than explicitly in your code.**
    The RTSJ adds a new form of asynchronous termination requests through the AsynchronouslyInterruptedException (AIE). But it only affects code that explicitly declares that it expects AIE to occur, and there are also deferred sections where the AIE will remain pending. Writing code that can handle AIE is very difficult because the normal Java rules are "bent" and finally blocks do not get executed inside AIE-enabled code.
    So as I said this is very hard to answer, it really depends what exactly you are running on and what you are trying to achieve.
    ** Note: some people used bytecode rewriting tools to add this kind of polling as a post-processing step. Perhaps that is something you might be able to do too.
    David Holmes

  • How to stop a thread forcefully. do reply urgent

    i would like to stop the thread . i have used stop() method and also i have tested by giving the threadname = null. but these two not worked . how to stop thread forcefully. urgent.
    with regards

    There is no direct way to stop the thread forcefully. If you have implemented the thread, modify the code so as to break on some flag.
    i.e.
    public void run()
    while (keepRunning)
    ...do some stuff here
    and provide some way to set the boolean keepRunning as false. The loop will exit and the thread will also be destroyed.

Maybe you are looking for

  • Passing values to between Pages from a PLSQL Procedure in third Page

    Hello, I have a form divided into 3 pages. The first Page is used to select Template which is used to call a screen Page 54 and Page 55 (Wizard Based screen). From Page 55 (third page) of my application, When I click on Finish Button (Submit Button),

  • The volume for "IMG_1038.JPG" cannot be found

    I copied some photos off a friend's memory stick directly into one of my iphoto folders. Now when i try to move or change the photos, the I get this message (in the topic). When i oped the thumbnail, i can see the enlarged photo, but after 3 seconds

  • Download/install error in CC App

    Hello, Whenever I try to download & install an app from the CC App installed on my Windows 7 64-bit laptop, I get this undefined download error (image attached).  The only way to fix this is to re-install the CC app then go and try again, which then

  • Garage Band not opening!

    Garage Band not opening due to conflicting third party plug-ins that migrated unintentionally from studio computer to Macbook (mainly T-Racks). Please advise on how to bypass or delete these rogue plug-ins. Many thanks!

  • Adding "th", "nd", "rd" or "st" to dates

    Hi All, Has anyone come across a date formatting function which can add the appropriate "th", "nd", "rd" or "st" to a date? I've done a fair bit of googling and haven't come across anything which takes into account that not all numbers ending in 1 sh