minh-hieu.pham
minh-hieu.pham

Reputation: 1079

Java Thread interruption: interrupt() vs stop()

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.

Upvotes: 0

Views: 1576

Answers (2)

WoDoSc
WoDoSc

Reputation: 2618

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
    }
}

Upvotes: 1

Andreas Wederbrand
Andreas Wederbrand

Reputation: 39991

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.

Upvotes: 0

Related Questions