JUC-java.util.concurrent学习(五)–
ForkJoin
做任务拆分合并
public class MyForkJoin extends RecursiveTask<Long> {
private Long start;
private Long end;
private Long temp=5000L;
public MyForkJoin(Long start, Long end) {
this.start = start;
this.end = end;
}
@Override
protected Long compute() {
if((end-start)<temp){//当差值小于temp时做累加
Long sum=0L;
for (Long i = start; i <= end; i++) {
sum+=i;
}
return sum;
}else {//当差值大于temp时做任务拆分
Long mid = (end + start) / 2;
MyForkJoin task1= new MyForkJoin(start,mid);
task1.fork();
MyForkJoin task2= new MyForkJoin(mid+1,end);
task2.fork();
return task1.join()+task2.join();
}
}
}
public class Test1 {
public static void main(String[] args) throws ExecutionException, InterruptedException {
Long start=System.currentTimeMillis();
System.out.println(test4(1L,1000000000L));
Long end=System.currentTimeMillis();
System.out.println(end-start);
}
public static Long test2(Long start,Long end){
Long sum=0L;
for (Long i = start; i <= end; i++) {
sum+=i;
}
return sum;
}
public static Long test3(Long start,Long end) throws ExecutionException, InterruptedException {
ForkJoinPool forkJoinPool=new ForkJoinPool();
MyForkJoin myForkJoin=new MyForkJoin(start,end);
ForkJoinTask<Long> submit = forkJoinPool.submit(myForkJoin);//使用ForkJoinPool提交任务,如果使用execute方法是没有返回值的
return submit.get();
}
public static Long test4(Long start,Long end) {
return LongStream.rangeClosed(start,end).parallel().reduce(0,Long::sum);
}
}
其中并行流时间对短,ForkJoin比较多,普通累加最多
ForkJoin有点像递归的思想每次对差值做比较,大了就继续拆分,直到差值小于临界值,然后做累加计算
使用CompletableFuture做异步回调
异步没有结果返回可以使用runAsync方法
CompletableFuture<Void> completableFuture = CompletableFuture.runAsync(()->{
try {
TimeUnit.SECONDS.sleep(2);
System.out.println("1111");
} catch (InterruptedException e) {
e.printStackTrace();
}
});
System.out.println("ssdadasda");
completableFuture.get();
异步有结果返回可以使用supplyAsync方法
CompletableFuture<String> supplyAsync = CompletableFuture.supplyAsync(() -> {
int i =10/0;
System.out.println("进入supplyAsync");
return "sfsafasf";
});
System.out.println(supplyAsync.whenComplete((t, u) -> {
System.out.println("t>>>" + t);//正常结果
System.out.println("u>>>" + u);//错误的返回信息
}).exceptionally((e) -> {
System.out.println(e.getMessage());
return "错了";
}).get());