【发布时间】:2017-05-14 14:07:15
【问题描述】:
未能在线程执行器上调用shutdown() 将导致应用程序永不终止。
关闭 ExecutorService 的最佳做法是:
ExecutorService service = null;
try {
service = Executors.newSingleThreadExecutor();
// add tasks to thread executor
…
} finally {
if (service != null) service.shutdown();
}
既然 Java 知道 try-with-resources 的概念,如果我们能做到这一点不是很好吗?
try (service = Executors.newSingleThreadExecutor())
{
// add tasks to thread executor
…
}
【问题讨论】:
-
好问题……我从来没有想过这个想法 ;-)
-
JDK 中有大量“资源丰富”的非
CloseableAPI
标签: java multithreading interface try-with-resources