第一句子网 - 唯美句子、句子迷、好句子大全
第一句子网 > 【Java并发编程】CountDownLatch

【Java并发编程】CountDownLatch

时间:2020-05-07 09:23:28

相关推荐

【Java并发编程】CountDownLatch

CountDownLatch是JUC提供的解决方案

CountDownLatch 可以保证一组子线程全部执行完牛后再进行主线程的执行操作。例如,主线程启动前,可能需要启动并执行若干子线程,这时就可以通过 CountDownLatch 来进行控制。

CountDownLatch是通过一个线程个数的计数器实现的同步处理操作,在初始化时可以为CountDownLatch设置一个线程执行总数,这样每当一个子线程执行完毕后都要执行减1操作,当所有的子线程都执行完毕后,CountDownLatch中保存的计数为0,则主线程恢复执行。

CountDownLatch类常用方法

实现代码:

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()方法)后主线程恢复执行。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。