Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java, how to stop threads

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?

like image 701
vedran Avatar asked Dec 09 '22 03:12

vedran


2 Answers

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();
    }
like image 60
Tomasz Nurkiewicz Avatar answered Dec 15 '22 00:12

Tomasz Nurkiewicz


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.

like image 30
annonymously Avatar answered Dec 15 '22 00:12

annonymously