如何阻止线程?

jen*_*fer 14 multithreading android

线程处于活动状态时,如何停止线程?我已经给了

if(thread.isAlive()){
    thread.stop();
}
Run Code Online (Sandbox Code Playgroud)

但是方法stop已被弃用并抛出异常

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)
Run Code Online (Sandbox Code Playgroud)

我们怎么解决这个问题?

Jak*_*org 37

一般情况下,您不会强行停止线程,因为它很危险.您设置了一个标志,告诉有问题的线程在受控情况下退出它的线程循环.

你的线程循环看起来沿着这些方向:

void run() {
  while (shouldContinue) {
    doThreadWorkUnit();
  }
}
Run Code Online (Sandbox Code Playgroud)

在其他地方你设置shouldContinue变量并等待线程完成:

...
thread.shouldContinue = false;
thread.join();
...
Run Code Online (Sandbox Code Playgroud)

(所有这些可能都不正确Java,因为我不做Java.将其视为伪代码并修改您的实际语言/线程库/等.)