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

3

27
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();
Hocus answered 6/5, 2011 at 17:53 Comment(5)
could you check the above code and help me to kill the threadHocus
See this post forward.com.au/javaProgramming/HowToStopAThread.htmlDooley
Have a look at Best Practice for killing a JavaME 1.2 thread?, it may help.Carnal
Uh...is this even compilable code?Malefic
Thread.currentThread().isAlive() can never be false, by definition. The code is pointless.Blinni
E
62

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.

Everetteeverglade answered 6/5, 2011 at 18:6 Comment(9)
@Nathan: +1, if I had seen this answer, I wouldn't have even bothered writing one of my own! ggMalefic
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.Alvinia
@Raze: wouldn't simply catching blocking I/O interrupts and interrupting the current thread suffice?Malefic
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.Alvinia
@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.Everetteeverglade
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.Alvinia
And the example quoted by @Hocus 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.Alvinia
@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?Fiveandten
@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.Everetteeverglade
M
14

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();
Malefic answered 6/5, 2011 at 18:18 Comment(3)
+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 :DCrowned
if I call threat.interrupt(); without calling Thread.sleep(1000) what will happen, and is this safe?Professed
@LovekushVishwakarma docs.oracle.com/javase/10/docs/api/java/lang/…Malefic
A
6

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.

Alvinia answered 6/5, 2011 at 18:0 Comment(6)
Using a flag for cancellation can be dangerous if combined with blocking queue.Stingaree
@Luke, are you talking about cases where thread might not exit because it is waiting on a queue?Alvinia
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.Stingaree
@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.Alvinia
@Stingaree 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.Lundy
@Lundy 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 callAlvinia

© 2022 - 2024 — McMap. All rights reserved.