欢迎您访问365答案网,请分享给你的朋友!
生活常识 学习资料

Java并发JUC(java.util.concurrent)ForkJoin/异步回调

时间:2023-07-10
ForkJoin

什么是 ForkJoin

ForkJoin 在 JDK 1.7 , 并行执行任务!提高效率。大数据量!

ForkJoin处理流程:工作窃取

试验代码:

MyForkJoinTask:

package icu.lookyousmileface.forkjoin;import java.util.concurrent.RecursiveTask;class MyForkJoinTask extends RecursiveTask { //开始和结束位置数 private Long start; private Long end; //临界值 private Long temp = 10000L; public MyForkJoinTask(Long start, Long end) { this.start = start; this.end = end; } //计算方法 @Override protected Long compute() { //小于临界值就进行计算不拆分 if ((end-start)

MainTask:

package icu.lookyousmileface.forkjoin;import java.util.concurrent.ExecutionException;import java.util.concurrent.ForkJoinPool;import java.util.concurrent.ForkJoinTask;import java.util.stream.LongStream;public class MainTask { public static void main(String[] args) throws ExecutionException, InterruptedException { //创建forkjoin池// ForkJoinPool forkJoinPool = new ForkJoinPool();// //创建自己的ForkJoin计算程序// ForkJoinTask forkJoinTask = new MyForkJoinTask(0L, 10_0000_0000L);// //提交计算任务// ForkJoinTask submit = forkJoinPool.submit(forkJoinTask);// //获得计算的结果// Long aLong = submit.get();// System.out.println(aLong); long result = LongStream.rangeClosed(0L, 10_0000_0000L).parallel().reduce(0, Long::sum); System.out.println(result); }}

异步回调

试验代码:

package icu.lookyousmileface.completables;import java.util.concurrent.CompletableFuture;import java.util.concurrent.ExecutionException;import java.util.concurrent.TimeUnit;public class CompletableUse { public static void main(String[] args) throws ExecutionException, InterruptedException {// //没有返回值的异步回调// CompletableFuture completableFuture = CompletableFuture.runAsync(()->{// try {// TimeUnit.SECONDS.sleep(3);// } catch (InterruptedException e) {// e.printStackTrace();// }// System.out.println(" 异步任务执行成功!");// });// System.out.println("main主线程");// //获取异步执行的结果// completableFuture.get(); //又返回值的异步回调 CompletableFuture completableFuture = CompletableFuture.supplyAsync(() -> { System.out.println(Thread.currentThread().getName()+":supplyAsync=>ok"); int sum = 10/0; return 1024; }); //编译 //编译成功 System.out.println(completableFuture.whenComplete((u1,u2)->{ System.out.println("t=>"+u1);//正常的返回结果 System.out.println("u=>"+u2);//错误信息 //编译失败 }).exceptionally((e)->{ e.printStackTrace(); return 2233; //错误的返回结果 }).get()); }}

Copyright © 2016-2020 www.365daan.com All Rights Reserved. 365答案网 版权所有 备案号:

部分内容来自互联网,版权归原作者所有,如有冒犯请联系我们,我们将在三个工作时内妥善处理。