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); }
ForkJoinPool 实战
最新推荐文章于 2023-11-04 12:10:07 发布
该代码示例展示了如何自定义ForkJoinPool的线程工厂,并使用ForkJoinPool进行并行处理。通过创建ForkJoinPool,提交Callable任务以及使用Stream的parallel方法,展示了多线程执行任务并打印当前线程名称的场景。每个任务间有3秒的睡眠间隔。
摘要由CSDN通过智能技术生成