美文网首页
CountDownLatch

CountDownLatch

作者: 笨笨哒2018 | 来源:发表于2018-08-23 10:54 被阅读0次

    一个同步辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个或多个线程一直等待。

    用给定的计数 初始化 CountDownLatch。由于调用了 countDown() 方法,所以在当前计数到达零之前,await 方法会一直受阻塞。之后,会释放所有等待的线程,await 的所有后续调用都将立即返回。这种现象只出现一次——计数无法被重置。如果需要重置计数,请考虑使用 CyclicBarrier

    CountDownLatch 是一个通用同步工具,它有很多用途。将计数 1 初始化的 CountDownLatch 用作一个简单的开/关锁存器,或入口:在通过调用 countDown() 的线程打开入口前,所有调用 await 的线程都一直在入口处等待。用 N 初始化的 CountDownLatch 可以使一个线程在 N 个线程完成某项操作之前一直等待,或者使其在某项操作完成 N 次之前一直等待。

    CountDownLatch 的一个有用特性是,它不要求调用 countDown 方法的线程等到计数到达零时才继续,而在所有线程都能通过之前,它只是阻止任何线程继续通过一个 await

    参考实例

    package com.example.java_lib;
    
    import java.util.concurrent.CountDownLatch;
    
    public class CountDownLatchDemo {
        
        public static void main(String[] args) throws InterruptedException{
            
            final CountDownLatch countDownLatch = new CountDownLatch(2){
                @Override
                public void await() throws InterruptedException {
                    super.await();
                    System.out.println(Thread.currentThread().getName() +  " count down is ok");
                }
            };
            
            Thread thread1 = new Thread(new Runnable() {
                @Override
                public void run() {
                    //do something
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + " is done");
                    countDownLatch.countDown();
                }
            }, "thread1");
            
            Thread thread2 = new Thread(new Runnable() {
                @Override
                public void run() {
                    //do something
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + " is done");
                    countDownLatch.countDown();
                }
            }, "thread2");
            
            
            thread1.start();
            thread2.start();
            
            countDownLatch.await();
        }
        
    }
    //打印结果
    //thread1 is done
    //thread2 is done
    //main count down is ok
    
    

    相关文章

      网友评论

          本文标题:CountDownLatch

          本文链接:https://www.haomeiwen.com/subject/yvspiftx.html