java 线程池 ForkJoinPool 的简单示例

ForkJoinPool 可以根据CPU的核数并行的执行,适合使用在很耗时的操作,可以充分的利用CPU执行任务。

ForkJoinPool 的UML类图:

 简单示例:

public class ForkJoinPoolTest {
    private static final int threads = 10;
    CountDownLatch countDownLatch = new CountDownLatch(threads);

    @Test
    public void test1() throws InterruptedException {
        System.out.println("-------- begin ----------");
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        for (int i = 0; i < threads; i++) {
            forkJoinPool.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        System.out.println("getParallelism=" + forkJoinPool.getParallelism());
                        System.out.println("getStealCount=" + forkJoinPool.getStealCount());
                        System.out.println(Thread.currentThread().getName());
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        countDownLatch.countDown();
                    }
                }
            });
        }
        countDownLatch.await();
        System.out.println("-------- end ----------");
    }
}

猜你喜欢

转载自blog.csdn.net/qq_38428623/article/details/86690058
今日推荐