How can I kill a thread? without using stop();

87,629

Solution 1

The alternative to calling stop is to use interrupt to signal to the thread that you want it to finish what it's doing. (This assumes the thread you want to stop is well-behaved, if it ignores InterruptedExceptions by eating them immediately after they are thrown and doesn't check the interrupted status then you are back to using stop().)

Here's some code I wrote as an answer to a threading question here, it's an example of how thread interruption works:

public class HelloWorld {

    public static void main(String[] args) throws Exception {
        Thread thread = new Thread(new Runnable() {

            public void run() {
                try {
                    while (!Thread.currentThread().isInterrupted()) {
                        Thread.sleep(5000);
                        System.out.println("Hello World!");
                    }
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        });
        thread.start();
        System.out.println("press enter to quit");
        System.in.read();
        thread.interrupt();
    }
}

Some things to be aware of:

  • Interrupting causes sleep() and wait() to immediately throw, otherwise you are stuck waiting for the sleep time to pass.

  • Note that there is no need for a separate boolean flag.

  • The thread being stopped cooperates by checking the interrupted status and catching InterruptedExceptions outside the while loop (using it to exit the loop). Interruption is one place where it's ok to use an exception for flow control, that is the whole point of it.

  • Setting interrupt on the current thread in the catch block is technically best-practice but is overkill for this example, because there is nothing else that needs the interrupt flag set.

Some observations about the posted code:

  • The posted example is incomplete, but putting a reference to the current thread in an instance variable seems like a bad idea. It will get initialized to whatever thread is creating the object, not to the thread executing the run method. If the same Runnable instance is executed on more than one thread then the instance variable won't reflect the right thread most of the time.

  • The check for whether the thread is alive is necessarily always going to result in true (unless there's an error where the currentThread instance variable is referencing the wrong thread), Thread#isAlive is false only after the thread has finished executing, it doesn't return false just because it's been interrupted.

  • Calling Thread#interrupted will result in clearing the interrupt flag, and makes no sense here, especially since the return value is discarded. The point of calling Thread#interrupted is to test the state of the interrupted flag and then clear it, it's a convenience method used by things that throw InterruptedException.

Solution 2

Typically, a thread is terminated when it's interrupted. So, why not use the native boolean? Try isInterrupted():

   Thread t = new Thread(new Runnable(){
        @Override
        public void run() {
            while(!Thread.currentThread().isInterrupted()){
                // do stuff         
            }   
        }});
    t.start();

    // Sleep a second, and then interrupt
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {}
    t.interrupt();

Solution 3

Good way to do it would be to use a boolean flag to signal the thread.

class MyRunnable implements Runnable {

    public volatile boolean stopThread = false;

    public void run() {
            while(!stopThread) {
                    // Thread code here
            }
    }

}

Create a MyRunnable instance called myrunnable, wrap it in a new Thread instance and start the instance. When you want to flag the thread to stop, set myrunnable.stopThread = true. This way, it doesn't get stopped in the middle of something, only where we expect it to get stopped.

Share:
87,629

Related videos on Youtube

greeshma
Author by

greeshma

Updated on July 09, 2022

Comments

  • greeshma
    greeshma almost 2 years
    Thread currentThread=Thread.currentThread();
            public void run()
            {               
    
                 while(!shutdown)
                {                               
                    try
                    {
                        System.out.println(currentThread.isAlive());
                    Thread.interrupted();
    
                    System.out.println(currentThread.isAlive());
                    if(currentThread.isAlive()==false)
                    {
                        shutdown=true;
                    }
                    }
                    catch(Exception e)
                    {
                        currentThread.interrupt();
                    }                   
                }
            }
    
        });
        thread.start();
    
  • mre
    mre almost 13 years
    @Nathan: +1, if I had seen this answer, I wouldn't have even bothered writing one of my own! gg
  • ardeee
    ardeee almost 13 years
    First of all, this code assumes that a sleep or other Interruptible blocking call is going to be used. This need not be the case. The code could be to do some complicated calculations. Using Thread interrupts need more care. Some IOs can also be interrupted, if there are multiple such IOs, we may need to clean up objects carefully, etc. I would suggest using a flag variable as a safer option generally.
  • mre
    mre almost 13 years
    @Raze: wouldn't simply catching blocking I/O interrupts and interrupting the current thread suffice?
  • ardeee
    ardeee almost 13 years
    It will definitely stop the thread, but this of this in the run() method: { try { while(...) {byte[] input = getChunkFromNetworkWhichHasCriticalData(); alertUser(input); } } catch(ClosedByInterruptException cbie) {...} }. Two points: Not all IO calls are interrupted, and so it may never exit. If IO call which will interrupt is called, then handling partially obtained data may be difficult. In many cases, like video streaming, this is not a concern. If there are multiple interruptible points in the code, it may get even more complex.
  • Nathan Hughes
    Nathan Hughes almost 13 years
    @Raze: care is definitely called for. that is why I left the Thread.currentThread().interrupt() in the example, to demonstrate making sure the interrupt flag is maintained. In any case, for the OP's purposes I don't think the flag is necessary, though it doesn't hurt anything and your example is well-implemented.
  • ardeee
    ardeee almost 13 years
    The points being: 1. There has to be calls in the code which are interruptible. 2. If handling code/data which has partially run/obtained/sent is important, design of the code has to be done carefully. When this kind of interruption and interrupt handling is not requried, it can be avoided. But there are many cases where using interrupts properly is recommended and is more efficient.
  • ardeee
    ardeee almost 13 years
    And the example quoted by @greeshma doesn't have a sleep in it, and I didn't make any assumptions. Besides, I have seen people I know implement audio multi casting with multiple threads, using interrupts to exit, and failing to flush the audio buffer in some cases, which leaves small bits of audio looping forever till the program exits.
  • Toby
    Toby almost 13 years
    +1, people like to roll their own (boolean) but you have to make it volatile and blar blar blar... using a standard interruption policy like isInterrupted feels more elegant :D
  • Abidi
    Abidi over 10 years
    @NathanHughes I came across your answer and it's pretty helpful, it's just that I can't understand the reason of calling interrupt again in the catch? Why would the same thread call interrupt again?
  • Nathan Hughes
    Nathan Hughes over 10 years
    @Abidi: in this case it doesn't matter. if you had nested components that all had to respond to interruption then you would need to do this to make sure everybody sees the interrupt.
  • John Mercier
    John Mercier almost 9 years
    This is a great answer! I have always implemented a separate flag but this makes much more sense. As far as closing resources properly goes, it is not a threading issue but an error handling issue. IO should be closed in a finally block not a try or catch block. This is so often messed up jdk7 came out with try-with-resources statements.
  • Luke
    Luke almost 8 years
    Using a flag for cancellation can be dangerous if combined with blocking queue.
  • ardeee
    ardeee almost 8 years
    @Luke, are you talking about cases where thread might not exit because it is waiting on a queue?
  • Luke
    Luke almost 8 years
    yeah basically if you have a blocking operation like queue.put within the while loop and your queue is full and all the consumers of the queue have finished then even if you set the flag to stop your task won't finish.
  • ardeee
    ardeee almost 8 years
    @luke, That's true for any operation that uses Object.wait or one of the many NIO calls, in which case Nathan's answer can be used with or without adding the flag as the case may be. However that may not work in a system where you the class doesn't have permission to interrupt (rare, but I've been there once), and more importantly, edge cases where thread hasn't started yet.
  • Lovekush Vishwakarma
    Lovekush Vishwakarma over 5 years
    if I call threat.interrupt(); without calling Thread.sleep(1000) what will happen, and is this safe?
  • mre
    mre over 5 years
  • user3740179
    user3740179 about 2 years
    @Luke can you tell me how to stop thread in the situation that you wrote? I mean when thread is blocking on queue and should be stoped.
  • ardeee
    ardeee about 2 years
    @user3740179 in that case you can use thread's interrupt method (See Nathan's answer ). If there are multiple calls which will do a wait, you should check isInterrupted after each such call