多线程异步执行,等待执行全部执行完成后,返回全部结果 CompletableFuture和Future以及CountDownLatch 使用

需求:需要异步执行多个任务,获取每个任务的结果。根据任务结果判断是否继续后面的操作
// 存储全部任务返回结果集合
    public static void main(String[] args) {
    
    
        List<CompletableFuture> objects = Collections.synchronizedList(new ArrayList<>());
        ExecutorService es = Executors.newFixedThreadPool(3);
        // 创建一个任务
        objects.add(CompletableFuture.supplyAsync(() -> {
    
    
                    try {
    
    
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
    
    
                        e.printStackTrace();
                    }
                    // if (Math.random() != 0.1) {
    
    
                    //     throw new RuntimeException("手动异常");
                    // }
                    return "任务1";
                }, es)
                .handle((result,e)->{
    
     // 返回 结果和异常信息,没有异常e返回null
                    System.out.println("结果和异常信息"+result+"-error:"+e);
                    return result;
                }));
        // 添加到任务集合
        // 添加第二个任务
        objects.add(CompletableFuture.supplyAsync(() -> {
    
    
            return "任务2";
        }));
        CompletableFuture<Void> voidCompletableFuture = CompletableFuture.allOf(objects.toArray(new CompletableFuture[objects.size()]));
        // join方法会阻塞线程,等待全部执行完成
        List<Object> collect = objects.stream().map(CompletableFuture::join).collect(Collectors.toList());
        System.out.println("全部执行结果:"+collect);
        System.out.println("是否全部完成:"+voidCompletableFuture.isDone());
        // 关闭线程池,否则main方法不会结束
        es.shutdown();
    }
方式二 使用Future ,示例:按循序执行,等获取到指定任务的结果后再继续执行
  ExecutorService executorService = Executors.newFixedThreadPool(3);
        Future<String> submit = executorService.submit(new Callable<String>() {
    
    
            @Override
            public String call() throws Exception {
    
    
                Thread.sleep(3000);
		// 需要处理异常
                // if(Math.random()!=0.3){
    
    
                //     throw new RuntimeException("手动异常");
                // }
                return "我是任务1结果";
            }
        });
        Future<String> submit2 = executorService.submit(new Callable<String>() {
    
    
            @Override
            public String call() throws Exception {
    
    
                Thread.sleep(2500);
                return "我是任务2结果";
            }
        });
       // 调用get时会阻塞线程,获取到结果后才向下进行
        String s = submit.get(); 
        String s2 = submit2.get();
        System.out.println("任务1:"+s);
        System.out.println("任务2:"+s2);
        System.out.println("执行完成");  

使用CountDownLatch实现 :一个比赛的示例
        CountDownLatch countDownLatch = new CountDownLatch(5);
        ThreadPoolExecutor tp = new ThreadPoolExecutor(5, 5, 10, TimeUnit.SECONDS, new LinkedBlockingDeque<>());
        tp.allowCoreThreadTimeOut(true);
        for (int i = 0; i < 5; i++) {
    
    
            int finalI = i + 1;
            Runnable runnable = new Runnable() {
    
    
                @Override
                public void run() {
    
    
                    Long ll = (long) (Math.random() * 1000);
                    try {
    
    
                        Thread.sleep(ll);
                    } catch (InterruptedException e) {
    
    
                        e.printStackTrace();
                    } finally {
    
    
                        countDownLatch.countDown();
                        System.out.println(finalI + "号选手,完成了比赛!:" + ll + "秒:" + Thread.currentThread().getName());
                    }
                }
            };
            // 提交任务
            tp.submit(runnable);
            // try {
    
    
            // 	// 添加任务并获取任务结果
            // 	String taskResult = (String) tp.submit(runnable).get(1, TimeUnit.SECONDS);
            // 	System.out.println(taskResult);
            // } catch (Exception e) {
    
    
            // 	e.printStackTrace();
            // }
        }
        System.out.println("等待5个运动员都跑完.....");
        countDownLatch.await();
        tp.shutdown(); // 关闭线程池
        System.out.println(tp.isShutdown());
        System.out.println(tp.isTerminated());
        System.out.println("所有人都跑完了,比赛结束。");

猜你喜欢

转载自blog.csdn.net/weixin_43051544/article/details/130064457