class SomeClass {
void go() {
//do stuff
shutdownAndAwaitTermination(pool);
System.exit(0);
}
public void shutdownAndAwaitTermination(ExecutorService pool) {
pool.shutdown();
try {
logger.log(Level.INFO, "Waiting for existing tasks to terminate");
if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
pool.shutdownNow();
if(!pool.awaitTermination(60, TimeUnit.SECONDS)) {
logger.log(Level.SEVERE, " ERROR: pool did not terminate");
}
}
} catch (InterruptedException ie) {
// (Re-)Cancel if current thread also interrupted
pool.shutdownNow();
// Preserve interrupt status
Thread.currentThread().interrupt();
}
}
}//end class
我试图安全,优雅地关闭水池,而不会遇到永远不会终止的风险。我需要了解您的专家8-)。当我致电shutdownAndAwaitTermination()
时,我对if (!pool.awaitTermination(60, TimeUnit.SECONDS))
块感到困惑。当方法go()
中的该行exectues exectues时,应用程序是否等待60秒(等待终止)?
2)您能解释一下捕获块中会发生什么吗?
1)nope它将以最大60秒等待,但如果所有任务完成了30秒后也可以返回。
2)如果当前线程被打断,则告诉您现在关闭的池池,而执行任务执行。比您再次中断以保持线程属性