So I create a thread
Thread personThread = new Thread(Person);
personThread.start();
/** Now to stop it **/
personThread.stop();
The problem is, when I try to compile I get: warning: [deprecation] stop() in Thread has been deprecated
. As I am to understand, this is no longer used method. How can I then completely stop a thread, irrelevant of it's status?
You should interrupt a thread, which is a gentle way of asking it to stop.
Shameless copy of myself:
final Thread thread = new Thread(someRunnable);
thread.start();
Instead of stop()
call interrupt()
:
thread.interrupt();
And handle the interruption manually in the thread:
while(!Thread.currentThread().isInterrupted()){
try{
Thread.sleep(10);
}
catch(InterruptedException e){
Thread.currentThread().interrupt();
}
Here is a page about that: How to Stop a Thread or a Task
... This article covers some of the background to stopping threads and the suggested alternatives and discusses why interrupt() is the answer. It also discusses interrupting blocking I/O and what else the programmer needs to do to ensure their threads and tasks are stoppable.
As far as Why Are Thread.stop, Thread.suspend, Thread.resume and Runtime.runFinalizersOnExit Deprecated? (Linked in previous article)
Because it is inherently unsafe. Stopping a thread causes it to unlock all the monitors that it has locked ... This behavior may be subtle and difficult to detect ... the user has no warning that his program may be corrupted. The corruption can manifest itself at any time after the actual damage occurs, even hours or days in the future.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With