如何停止一个线程?线程

由网友(浮生辞)分享简介:当一个线程是活的,我怎么能停止线程?我已经给像When a thread is alive, how can I stop the thread? I have given likeif(thread.isAlive()){thread.stop();}但该方法停止去precated并抛出异常but the m...

当一个线程是活的,我怎么能停止线程?我已经给像

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

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

但该方法停止去precated并抛出异常

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?

推荐答案

在一般情况下,你就不要强行终止线程,因为它是危险的。您可以设置一个标志,告诉线程问题,从它的线程循环在受控的情况下退出。

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();
  }
}

和其他地方将 shouldContinue 变量,等待线程完成:

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

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

(所有这一切都可能是不正确的Java,因为我没有做Java的,认为它是伪code和修改您的实际语言/线程库的/ etc。)

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

阅读全文

相关推荐

最新文章