多线程门闩CountDownLatch的玩法

CountDownLatch,一个同步辅助类,在完成特定的操作之前,它让一个或多个线程一直等待,

构造函数:new CountDownLatch(2);初始化门闩的长度为2;

它有两个主要方法:latch.await(),当前线程等待,直到门闩的值为0,线程才往下执行;

                                 latch.countDown(),门闩值减一;

使用await在主线程阻塞,每个子线程执行完了,就调用latch.countDown()一次,知道最后门闩为0,解开主线程的等待;

比如主线程开启多个子线程,当所有子线程都执行完了,主线程才能继续往下执行,如下:


publicclassTest {

   publicstaticvoidmain(String[] args) {

     finalCountDownLatch latch =newCountDownLatch(2);

     newThread(){

     publicvoidrun() {

          try{

              System.out.println("子线程"+Thread.currentThread().getName()+"正在执行");

              System.out.println("子线程"+Thread.currentThread().getName()+"执行完毕");

              latch.countDown();

          }catch(InterruptedException e) {

            e.printStackTrace();

          }

  };

}.start();

newThread(){

publicvoidrun() {

try{

       System.out.println("子线程"+Thread.currentThread().getName()+"正在执行");

       System.out.println("子线程"+Thread.currentThread().getName()+"执行完毕");

       latch.countDown();

}catch(InterruptedException e) {

        e.printStackTrace();

}

};

}.start();

try{

     System.out.println("等待2个子线程执行完毕...");

     latch.await();

     System.out.println("2个子线程已经执行完毕");

     System.out.println("继续执行主线程");

}catch(InterruptedException e) {

e.printStackTrace();

}

}

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容