多线程之ForkJoinPool(since 1.7)

2020-09-01  本文已影响0人  飞行员舒克_ed03
    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();
        }
    }
}
上一篇 下一篇

猜你喜欢

热点阅读