JAVA 等待并发任务结束的几种方式

有时候需要并发执行一系列任务,等待所有的任务结束后再进行一些操作,下面介绍几种实现方式。

假设需要执行n个任务,任务为:

        Runnable r = () -> {
            try {
                Thread.sleep(new Random().nextInt(1000));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        };

1 暴力方式

        List<Thread> threads = IntStream.range(0, n).boxed()
        .map(a -> new Thread(r)).collect(Collectors.toList());
        threads.forEach(Thread::start);
        for (Thread thread : threads) {
            try {
                thread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

这种方式比较原始,如果业务使用线程池,就没法操作了。

2 改写业务代码

    如果使用线程池提交任务,则可以使用CountDownLatch,每个任务执行完时,CountDownLatch#countDown, 提交完任务后,CountDownLatch#await,等待任务执行完。不过这种方式入侵了业务逻辑,不够优雅。

    @AllArgsConstructor
    private class MyRunnable implements Runnable {
        private CountDownLatch latch;
        @Override
        public void run() {
            try {
                Thread.sleep(new Random().nextInt(1000));
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                latch.countDown();
            }
        }
    }
        CountDownLatch latch = new CountDownLatch(n);
        ExecutorService executorService = Executors.newCachedThreadPool();
        IntStream.range(0, n).boxed()
                .forEach(a -> executorService.submit(new MyRunnable(latch)));
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

3 不改写业务代码

使用CompletableFuture,可以避免在业务逻辑中嵌入任务控制逻辑,使用CompletableFuture#whenComplete可以在任务执行完后回调传入的逻辑,这样可以避免任务控制逻辑入侵业务逻辑。

        CountDownLatch latch = new CountDownLatch(n);
        ExecutorService executorService = Executors.newCachedThreadPool();
        IntStream.range(0, n).boxed()
                .forEach(a -> CompletableFuture.runAsync(r, executorService)
                        .whenComplete(((aVoid, throwable) -> latch.countDown())));
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

4 继续优化

上面的方式虽然可行,但不够优雅,需要用CountDownLatch来做控制。实际上使用CompletableFuture提供的接口,完全可以去掉CountDownLatch。

        ExecutorService executorService = Executors.newCachedThreadPool();
        CompletableFuture[] futures = IntStream.range(0, n).boxed()
                .map(a -> CompletableFuture.runAsync(r, executorService))
                .toArray(CompletableFuture[]::new);
        CompletableFuture.allOf(futures).join();

// 也可以直接使用ForkJoinPool的默认线程池

        CompletableFuture[] futures = IntStream.range(0, n).boxed()
                .map(a -> CompletableFuture.runAsync(r))
                .toArray(CompletableFuture[]::new);
        CompletableFuture.allOf(futures).join();

// 若需要异步执行两个不同的方法 f1()和f2(), 则可以如下执行

        CompletableFuture a = CompletableFuture.runAsync(() -> f1());
        CompletableFuture b = CompletableFuture.runAsync(() -> f2());
        CompletableFuture.allOf(new CompletableFuture[]{a, b}).join();

* 如果任务有返回值,使用supplyAsync即可。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值