【发布时间】:2015-03-09 21:21:47
【问题描述】:
这里有关于设计的一般问题。我有一些线程需要在后台保持运行,基本上是一些数据库上传/故障处理任务。都具有以下流模式:
public class Worker implements Runnable {
private AtomicBoolean isAlive = new AtomicBoolean(true);
....
public void run() {
while (isAlive.get()) {
// do some work here, slightly heavy
if (Thread.interrupted()) {
// checking Thread.interrupted() as the code above
// can take a while and interrupt may happen before
// it gets here.
isAlive.setBoolean(false);
break; // to exit faster
}
try { Thread.sleep(sleepTime); }
catch (InterruptedException e) {
isAlive.setBoolean(false);
break; // to exit faster
}
}
cleanUp(); // e.g. close db connections etc
}
}
现在我希望能够中断线程,以便它可以优雅地跳出 while 循环并运行 cleanUp() 方法。
有很多方法可以做到这一点,这里列举几个:
-
在
Threads中关闭Runnables,然后使用interrupt()方法:List<Thread> threadList =... for (int i < 0; i < threadCount; i++) { Thread t = new Thread(new Worker()); threadList.add(t); t.start() } // later for (Thread t : threadList) { t.interrupt(); } -
ThreadPoolExecutor,然后使用
shutdownNow():ThreadPoolExecutor executor = new ....; executor.execute(new Worker()); // some lines else later executor.shutdownNow(); // shutdown() doesn't interrupt?
处理此类工作流的方法是什么?为什么?欢迎所有想法。
【问题讨论】:
-
cleanUp();应该在finally块中,除非您想在发生意外异常时保持数据库连接打开。
标签: java multithreading concurrency interrupt