CountDownLatch是JUC提供的解决方案
CountDownLatch 可以保证一组子线程全部执行完牛后再进行主线程的执行操作。例如,主线程启动前,可能需要启动并执行若干子线程,这时就可以通过 CountDownLatch 来进行控制。
CountDownLatch是通过一个线程个数的计数器实现的同步处理操作,在初始化时可以为CountDownLatch设置一个线程执行总数,这样每当一个子线程执行完毕后都要执行减1操作,当所有的子线程都执行完毕后,CountDownLatch中保存的计数为0,则主线程恢复执行。
CountDownLatch类常用方法
方法 | 描述 |
---|---|
public CountDownLatch(int count) | 定义等待子线程总数 |
public void await() throws InterruptedException | 主线程阻塞,等待子线程执行完毕 |
public void countDown() | 子线程执行完后减少等待数量 |
public long getCount() | 获取当前等待数量 |
实现代码:
public static void main(String[] args) throws Exception {int n = 3;String[] tasks = {"发短信完毕", "发微信完毕", "发QQ完毕"};int[] executeTimes = new int[]{2, 5, 1};CountDownLatch countDownLatch = new CountDownLatch(n);ExecutorService executorService = Executors.newFixedThreadPool(n);long start = System.currentTimeMillis();for (int i = 0; i < n; i++) {int finalI = i;executorService.submit(() -> {try {TimeUnit.SECONDS.sleep(executeTimes[finalI]);System.out.println(tasks[finalI]);} catch (InterruptedException e) {e.printStackTrace();} finally {countDownLatch.countDown();}});}countDownLatch.await();System.out.println("所有消息都发送完毕了,执行主线程任务。\n耗时ms:" + (System.currentTimeMillis() - start));// 不要忘记关闭线程池,不然会导致主线程阻塞无法退出executorService.shutdown();
}
本程序利用 CountDownLatch 定义了要等待的子线程数量,这样在该统计数量不为0的时候,主线代码暂时挂起,直到所有的子线程执行完毕(调用countDown()方法)后主线程恢复执行。
上一篇:光速c数列的猜想:光猜
下一篇:【数据库】MySQL数据库基础