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.
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.
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.
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 (withisInterrupted()
method), and exit when you want. For instance: