public static void testForkJoinPool() throws InterruptedException {
ForkJoinPool forkJoinPool = new ForkJoinPool();
try{
for (int i = 0; i < 10; i++) {
ATask aTask = new ATask(i);
ForkJoinTask forkJoinTask = ForkJoinTask.adapt(aTask);
forkJoinPool.execute(forkJoinTask);
}
//awaitTermination 之前必须执行 forkJoinPool.shutdown(); 否则只能等到超时后才能结束
forkJoinPool.shutdown();
forkJoinPool.awaitTermination(20, TimeUnit.SECONDS);
System.out.println("finish");
} finally {
if (!forkJoinPool.isShutdown()) {
//如果存在异常shutdown被打断,放弃这次计算,并取消正在执行的任务,直接shutdownNow
forkJoinPool.shutdownNow();
}
}
}
网友评论