我有一个实现Runnable接口的类,其run()定义如下:
class MyTask implements Runnable {
// ...
// active is a boolean flag set to true at the beginning,
// but which can be set to false from outside of the task
// ...
@Override
public void run() {
if (active) {
// Do something
}
}
}
我将它添加到ScheduledExecutorService以定期运行:
ScheduledExecutorService executor = Executors.newScheduledThreadPool(2);
executor.scheduleAtFixedRate(new MyTask(), 10, 10, TimeUnit.SECONDS);
当满足某个条件时,我将'active'设置为false,if块中的代码不再执行,这很好。但这真的是我需要做的吗?如果我理解正确,run函数将继续被调用,因为线程永远不会死。我想确保这个线程简单地停止,并且它以一种不会被中断的方式停止,如果在线程执行时应该停止线程的条件(在这种情况下,线程应该不间断地完成工作,但绝不再重复)。