当我试图弄清楚如何停止具有多个线程的程序中的线程时,
我是suggested调用一个实际上设置一个标志来告诉线程停止做实际工作的方法,如下所示:
public class ThreadTobeTerminated implements Runnable {
private static final Logger LOGGER = LoggerFactory.getLogger(IndexProcessor.class);
private volatile boolean running = true;
public void terminate() {
running = false;
}
@Override
public void run() {
while (running) {
try {
LOGGER.debug("Doing some real work ,like Counting...");
for(int i=0;i<100;i++){}
} catch (InterruptedException e) {
LOGGER.error("Exception", e);
running = false;
}
}
}
}
当我想停止这个步骤时,我会调用threadInstance.terminate();
。
我不需要真正停止这个线程吗?
为什么我应该让这个线程做一些无用的工作(调用方法run
,测试标志running==false
然后返回)?我的意思是:这是浪费时间,不是吗?
最佳答案
当执行范围超出run()
方法时,线程就会停止,因此当while
循环被破坏时,线程就会停止。
如果情况需要,这还允许您进行一些清理:
public void run() {
while (running) {
try {
LOGGER.debug("Doing some real work ,like Counting...");
for(int i=0;i<100;i++){}
} catch (InterruptedException e) {
LOGGER.error("Exception", e);
running = false;
}
}
//Clean up
}
上述方法允许您对线程如何停止以及之后发生的情况进行一些控制,而不是直接杀死它,这可能会导致各种问题。
关于java - 为什么我们使用标志来停止线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29392643/