ForkJoinPool 实战

该代码示例展示了如何自定义ForkJoinPool的线程工厂,并使用ForkJoinPool进行并行处理。通过创建ForkJoinPool,提交Callable任务以及使用Stream的parallel方法,展示了多线程执行任务并打印当前线程名称的场景。每个任务间有3秒的睡眠间隔。
摘要由CSDN通过智能技术生成
public static void main(String[] args) throws ExecutionException, InterruptedException {

    ForkJoinPool.ForkJoinWorkerThreadFactory forkJoinThreadFactory = pool -> {
        ForkJoinWorkerThread thread = ForkJoinPool.defaultForkJoinWorkerThreadFactory.newThread(pool);
        thread.setName("computation-thread-" + thread.getPoolIndex());
        return thread;
    };

    ForkJoinPool forkJoinPool = new ForkJoinPool(20, forkJoinThreadFactory, null, false);

    long start = System.currentTimeMillis();
    List<Callable<Object>> collect = Stream.of(1, 2, 3, 4, 5, 6).map(x -> {
        return (Callable<Object>) () -> {
            System.out.println(x + "====" + Thread.currentThread().getName());
            ThreadUtil.sleep(3000);
            return true;
        };

    }).collect(Collectors.toList());
    forkJoinPool.invokeAll(collect);
    System.out.println(System.currentTimeMillis() - start);

    start = System.currentTimeMillis();
    ForkJoinTask forkJoinTask1 = forkJoinPool.submit(() -> {
        //转换并执行
        Stream.of(1, 2, 3, 4, 5, 6).parallel().forEach(taskDO -> {
            System.out.println(taskDO + "====" + Thread.currentThread().getName());
            ThreadUtil.sleep(3000);
        });
    });
    forkJoinTask1.get();
    System.out.println(System.currentTimeMillis() - start);

    start = System.currentTimeMillis();
    ForkJoinTask forkJoinTask2 = forkJoinPool.submit(() -> {
        //转换并执行
        Stream.of(1, 2, 3, 4, 5, 6).forEach(taskDO -> {
            System.out.println(taskDO + "====" + Thread.currentThread().getName());
            ThreadUtil.sleep(3000);
        });
    });
    forkJoinTask2.get();
    System.out.println(System.currentTimeMillis() - start);

    
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值