多线程异步执行,等待执行全部执行完成后,返回全部结果 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("所有人都跑完了,比赛结束。");

  • 3
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用CountDownLatch配合Future和Callable实现返回线程的结果。以下是示例代码: ```java import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class ThreadDemo { public static void main(String[] args) throws InterruptedException, ExecutionException { ExecutorService executorService = Executors.newCachedThreadPool(); CountDownLatch latch = new CountDownLatch(1); Future<Integer> future = executorService.submit(new Callable<Integer>() { @Override public Integer call() throws Exception { int result = 0; // 执行一些耗时的操作 for (int i = 0; i < 1000000; i++) { result += i; } return result; } }); new Thread(() -> { try { latch.await(); System.out.println("子线程返回结果:" + future.get()); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } }).start(); // 唤醒等待的子线程 latch.countDown(); executorService.shutdown(); } } ``` 在上面的代码中,我们创建了一个CountDownLatch对象,然后在主线程中启动了一个子线程,子线程执行了一些耗时的操作,返回了结果。在主线程中,我们使用Future对象获取了子线程返回结果,并且在启动了一个新的线程来处理这个返回结果。在新线程中,我们使用CountDownLatch的await()方法等待线程调用countDown()方法唤醒它,然后再通过Future的get()方法获取子线程返回结果。最后,我们调用ExecutorService的shutdown()方法关闭线程池。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值