JUC-java.util.concurrent学习(五)--ForkJoin,CompletableFuture

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());
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值