【发布时间】:2021-03-19 23:28:00
【问题描述】:
我想优雅地关闭一个线程。但是,一旦启动关闭,线程应该在结束正常操作后执行一些关闭操作。
两个线程都使用睡眠和/或等待并处理 InterruptedException,它们还在循环中处理任务,只需几毫秒。所以我希望 while 循环结束,因为 Thread.currentThread().isInterrupted() 变为“真”。
问题是我的代码有时会得到日志“SHUTDOWN”,有时却没有。我也只是有时会得到“中断”,这是我当然理解的。对于另一个类似的线程,我永远不会得到“SHUTDOWN”。
ExecutorService executor = Executors.newFixedThreadPool(2);
executor.execute(new Test());
Thread.sleep(10000);
executor.shutdown();
try {
if(this.executor.awaitTermination(60, TimeUnit.SECONDS)) {
this.loggerFactory.getLogger(this.getClass()).info("CLOSED (GRACEFULLY)!");
} else {
this.executor.shutdownNow();
this.loggerFactory.getLogger(this.getClass()).info("CLOSED (IMMEDIATELY)!");
}
} catch(InterruptedException e) {
this.executor.shutdownNow();
this.loggerFactory.getLogger(this.getClass()).info("CLOSED (IMMEDIATELY)!");
}
class Test implements Runnable {
private volatile boolean isRunning = true;
@Override
public void run() {
try {
while(!Thread.currentThread().isInterrupted()) {
while(!this.isRunning) {
synchronized(this) {
this.wait();
}
}
// DO SOMETHING LASTING A FEW MILLISECONDS
Thread.sleep(500);
}
} catch(InterruptedException e) {
this.loggerFactory.getLogger(this.getClass()).info("INTERRUPTED!");
}
this.loggerFactory.getLogger(this.getClass()).info("SHUTDOWN!");
// DO SOME SHUTDOWN OPERATION
}
}
【问题讨论】:
-
所以你希望线程总是执行一些关闭操作,而不管它们是如何被“告知”停止的?
-
这是正确的。
-
在我看来,可能抛出了一些你没有看到的异常。将任务缩小并从中移除关闭活动会很好。
-
@Martin 谁将 isRunning 设置为 false?
-
@dreamcrash 一个停止方法。但这与我的问题无关,也没有使用。实际上还有一个 start 方法将其设置为 true。
标签: java multithreading