我通过实现可运行接口创建了类,然后在我项目的其他类中创建了许多线程(近 10 个)。
如何停止其中一些线程?
原文由 svkvvenky 发布,翻译遵循 CC BY-SA 4.0 许可协议
我通过实现可运行接口创建了类,然后在我项目的其他类中创建了许多线程(近 10 个)。
如何停止其中一些线程?
原文由 svkvvenky 发布,翻译遵循 CC BY-SA 4.0 许可协议
如何停止通过实现可运行接口创建的线程?
有许多方法可以停止线程,但所有这些方法都需要特定的代码来完成。停止线程的典型方法是设置线程经常检查的 volatile boolean shutdown
字段:
// set this to true to stop the thread
volatile boolean shutdown = false;
...
public void run() {
while (!shutdown) {
// continue processing
}
}
您还可以中断导致 sleep()
、 wait()
和其他一些方法抛出 InterruptedException
的线程。您还应该使用以下方法测试线程中断标志:
public void run() {
while (!Thread.currentThread().isInterrupted()) {
// continue processing
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// good practice
Thread.currentThread().interrupt();
return;
}
}
}
请注意,使用 interrupt()
中断线程 不一定 会立即引发异常。只有当您处于可中断的方法中时,才会抛出 InterruptedException
。
如果您想将 shutdown()
方法添加到实现 Runnable
的类中,您应该定义自己的类,例如:
public class MyRunnable implements Runnable {
private volatile boolean shutdown;
public void run() {
while (!shutdown) {
...
}
}
public void shutdown() {
shutdown = true;
}
}
原文由 Gray 发布,翻译遵循 CC BY-SA 3.0 许可协议
15 回答8.4k 阅读
8 回答6.2k 阅读
1 回答4k 阅读✓ 已解决
3 回答6k 阅读
3 回答2.2k 阅读✓ 已解决
2 回答3.1k 阅读
2 回答3.8k 阅读
The simplest way is to
interrupt()
it, which will causeThread.currentThread().isInterrupted()
to returntrue
, and may also throw anInterruptedException
under certain circumstances where线程正在 _等待_,例如Thread.sleep()
,otherThread.join()
,object.wait()
等。在
run()
方法中,您需要捕获该异常和/或定期检查Thread.currentThread().isInterrupted()
值并执行某些操作(例如,突破)。Note: Although
Thread.interrupted()
seems the same asisInterrupted()
, it has a nasty side effect: Callinginterrupted()
clears theinterrupted
flag, whereas callingisInterrupted()
没有。其他非中断方法涉及使用正在运行的线程监视的“停止”(
volatile
)标志。