使用ExecutorService线程池,必须显式调用shutdown方法,否则线程池状态一直是运行中,程序不会退出。
这样如果重复调用的话,线程数会一直增长。
”’
public static void main(String[] args) {
SnapshotTest test = new SnapshotTest();
test.threadPoolTest();
System.out.println(“end”);
}
private void threadPoolTest() {
final ExecutorService threadPool = Executors.newFixedThreadPool(5);
ExecutorCompletionService<String> ecs = new ExecutorCompletionService(threadPool);
List<Future<String>> futureResult = new ArrayList<>();
for (int i = 0; i < 10; i++) {
futureResult.add(ecs.submit(new Callable<String>() {
@Override
public String call() throws Exception {
System.out.println("abc");
Thread.sleep(1000);
return "abc";
}
}));
}
try {
threadPool.shutdown();
} catch (Exception e) {
e.printStackTrace();
}
}
”’