Java Thread interruption: interrupt() vs stop()

1.5k Views Asked by At

I have a problem when working with thread in Java. What is the method preferred between interrupt() and stop() for interrupting a thread in Java? And why?

Thanks for any responses.

2

There are 2 best solutions below

0
On

Theoretically, with the manner you posed the question, neither of them, a thread should understand by itself when it has to terminate, through a synchronized flag.

And this is done by using the interrupt() method, but you should understand that this 'works' only if your thread is in a waiting/sleeping state (and in this case an exception is thrown), otherwise you must check yourself, inside the run() method of your thread, if the thread is interrupted or not (with isInterrupted() method), and exit when you want. For instance:

public class Test {
    public static void main(String args[]) {
        A a = new A(); //create thread object
        a.start(); //call the run() method in a new/separate thread)
        //do something/wait for the right moment to interrupt the thread
        a.interrupt(); //set a flag indicating you want to interrupt the thread

        //at this point the thread may or may not still running 

    }
}

class A extends Thread {

    @Override
    public void run() { //method executed in a separated thread
        while (!this.isInterrupted()) { //check if someone want to interrupt the thread
            //do something          
        } //at the end of every cycle, check the interrupted flag, if set exit
    }
}
3
On

Thread.stop() has been deprecated in java 8 so I would say that Thread.interrupt() is the way to go. There is a lengthy explanation over at oracles site. It also gives a good example of how to work with threads.