4

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?

vedran
  • 2,167
  • 9
  • 29
  • 47
  • You can't without serious repercussions which is exactly why stop and co are deprecated. – Voo Dec 17 '11 at 22:47
  • 2
    Did you look at the documentation? –  Dec 17 '11 at 22:48
  • Relevant question and accepted answer: http://stackoverflow.com/questions/7038063/stop-method-in-a-thread – melihcelik Dec 17 '11 at 22:51
  • possible duplicate of [How to stop a java thread gracefully?](http://stackoverflow.com/questions/3194545/how-to-stop-a-java-thread-gracefully) – Greg Hewgill Dec 17 '11 at 22:58

3 Answers3

6

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();
    }
Community
  • 1
  • 1
Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
4

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.

annonymously
  • 4,708
  • 6
  • 33
  • 47
4

The correct way to stop a thread is to call the method interrupt() on it and check whether the thread has been interrupted periodically while executing.

dplante
  • 2,445
  • 3
  • 21
  • 27
Reverend Gonzo
  • 39,701
  • 6
  • 59
  • 77