美文网首页
多线程之ForkJoinPool(since 1.7)

多线程之ForkJoinPool(since 1.7)

作者: 飞行员舒克_ed03 | 来源:发表于2020-09-01 09:44 被阅读0次
        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();
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:多线程之ForkJoinPool(since 1.7)

          本文链接:https://www.haomeiwen.com/subject/pdvmsktx.html