How to stop a thread?

2019-01-05 05:53发布

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?

4条回答
smile是对你的礼貌
2楼-- · 2019-01-05 06:27

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.

查看更多
男人必须洒脱
3楼-- · 2019-01-05 06:28

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
    ..
 }
查看更多
我欲成王,谁敢阻挡
4楼-- · 2019-01-05 06:37

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

Thread.interrupt();

So that you can also save the state of thread.

查看更多
该账号已被封号
5楼-- · 2019-01-05 06:40

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.)

查看更多
登录 后发表回答