如何停止一个线程? [英] How to stop a thread?

查看:159
本文介绍了如何停止一个线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这篇关于如何停止一个线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆