14

When a thread is alive, how can I stop the thread? I have given like

if(thread.isAlive()){
    thread.stop();
}

but the method stop is deprecated and is throwing an exception

01-21 14:12:40.188: ERROR/global(535):     Deprecated Thread methods are not supported.
01-21 14:12:40.188: ERROR/global(535):    java.lang.UnsupportedOperationException
01-21 14:12:40.188: ERROR/global(535):     at java.lang.VMThread.stop(VMThread.java:85)
01-21 14:12:40.188: ERROR/global(535):     at java.lang.Thread.stop(Thread.java:1379)
01-21 14:12:40.188: ERROR/global(535):     at java.lang.Thread.stop(Thread.java:1344)

How can we solve this?

BenMorel
  • 34,448
  • 50
  • 182
  • 322
jennifer
  • 8,133
  • 22
  • 69
  • 96

4 Answers4

37

In general, you don't forcibly stop threads because it's dangerous. You set a flag that tells the thread in question to exit from it's thread loop under controlled circumstances.

Your thread loop looks something along these lines:

void run() {
  while (shouldContinue) {
    doThreadWorkUnit();
  }
}

And somewhere else you set the shouldContinue variable and wait for the thread to finish:

...
thread.shouldContinue = false;
thread.join();
...

(All this is likely not correct Java, since I don't do Java. View it as pseudo code and modify for your actual language/thread library/etc.)

Jakob Borg
  • 23,685
  • 6
  • 47
  • 47
  • 1
    I agree with you, but what about non-looping Threads? I mean more like heavy IO operations, is it a good practice to call "interrupt()"? – mdelolmo Jan 21 '11 at 08:50
  • @mdelolmo I'd say no, you still want to set a cancel flag and basically ignore it. If it's blocking, it's not using any CPU anyway. But I'm sure there are other opinions on this as well. Note my weasel words "In general" in the post - I'm sure there are exceptions. Somebody's bound to bring up an embedded environment or somesuch where you always interrupt your threads. ;) – Jakob Borg Jan 21 '11 at 08:53
  • If you are using a HandlerThread, just call quit() or quitSafely() and it does exactly this on your behalf. For threads with long blocking sections, you may want to insert checks periodically to see if the thread needs to quit. – Dorje Aug 28 '13 at 15:52
3

Here's what the Java people have to say about why not to call thread.stop and what to do instead.

http://download.oracle.com/javase/1.5.0/docs/guide/misc/threadPrimitiveDeprecation.html

The short answer is, you allow the thread entry point function to return.

Sparky
  • 8,437
  • 1
  • 29
  • 41
2

Better you have to use this method of thread,to stop it.

Thread.interrupt();

So that you can also save the state of thread.

Jay Vyas
  • 2,674
  • 5
  • 27
  • 58
0

In a non looping thread implmentation, you can always use some thing like this at the very beginning of thread code as:

void run() {
    if (!shouldContinue) { 
       return 1; 
    } 
    .. 
    then rest of the thread code
    ..
 }
TheCottonSilk
  • 8,662
  • 2
  • 26
  • 37