有时候需要并发执行一系列任务,等待所有的任务结束后再进行一些操作,下面介绍几种实现方式。
假设需要执行n个任务,任务为:
Runnable r = () -> { try { Thread.sleep(new Random().nextInt(1000)); } catch (InterruptedException e) { e.printStackTrace(); } };
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(); } }
这种方式比较原始,如果业务使用线程池,就没法操作了。
如果使用线程池提交任务,则可以使用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(); }
使用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(); }
上面的方式虽然可行,但不够优雅,需要用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();
* 如果任务有返回值,使用supplyAsync即可。