JUC里的同步组件

1.countDownLatch(闭锁)

countDownLatch基于AQS的成员变量state实现的计数器,每次执行countDown()方法时,计数器减1,执行await()方法会阻塞线程直到计数器为0。我的理解 就类似一个大门一样,当计数器为0 大门才会打开,所有的线程才能通过大门,继续执行。一般用在多任务执行,最后汇总(即最终的操作依赖于所有子任务执行完成的结果),所有子任务完成之后,才能进行最终操作,代码示例如下

public static void main(String[] args) throws InterruptedException { CountDownLatch countDownLatch = new CountDownLatch(2); ExecutorService executorService = Executors.newFixedThreadPool(2); executorService.submit(()->{ try { Thread.sleep(10); System.out.println("child threadOne over"); } catch (InterruptedException e) { e.printStackTrace(); }finally { countDownLatch.countDown(); } }); executorService.submit(()-> { try { Thread.sleep(10); System.out.println("child threadTwo over"); } catch (InterruptedException e) { e.printStackTrace(); }finally { countDownLatch.countDown();//原子操作,同时只能有一个线程操作计数器 } }); Thread.sleep(1000); System.out.println("wait all child thread over"); try { countDownLatch.await(2, TimeUnit.SECONDS);//调用await()会一直阻塞,直到countDown计数器为0 (大门一直关闭,直到计数器为0打开),并发继续执行 System.out.println("all child thread over"); //调用await(2, TimeUnit.SECONDS) ,超过这个时间,(大门打开)线程不阻塞,并发继续执行 } catch (InterruptedException e) { e.printStackTrace(); } executorService.shutdown(); }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zyyzjx.html