CountDownLatch笔记

能使一个线程等待其他线程各自执行完毕后再执行
是通过一个计数器来实现的,计数器的初始值是线程的数量。每当一个线程执行完毕后,计数器的值就-1,当计数器的值为0时,表示所有线程都执行完毕,然后在闭锁上等待的线程就可以恢复工作了。

void await()   调用await方法的线程会被挂起,等待直到count值为0才继续执行
boolean await(long timeout, TimeUnit unit)   等待一定的时间,如果count还没变为0就继续执行
void countDown()   使count的值减1

例子1

public class Test1 {
    public static void main(String[] args) {
        final CountDownLatch latch = new CountDownLatch(2);
        System.out.println("主线程开始执行......");
        
        ExecutorService es1 = Executors.newSingleThreadExecutor();
        es1.execute(new Runnable() {
            
            @Override
            public void run() {
                try {
                    Thread.sleep(3000);
                    System.out.println("子线程:"+Thread.currentThread().getName()+"执行");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                latch.countDown();
            }
        });
        es1.shutdown();
        
        ExecutorService es2 = Executors.newSingleThreadExecutor();
        es2.execute(new Runnable() {
            
            @Override
            public void run() {
                try {
                    Thread.sleep(3000);
                    System.out.println("子线程:"+Thread.currentThread().getName()+"执行");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                latch.countDown();
            }
        });
        es2.shutdown();
        System.out.println("开始等待两个线程执行完毕.......");
        
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        
        System.out.println("两个子线程执行完毕,主线程继续执行");
    }
}

 

posted @ 2021-03-28 15:18  xtu熊大  阅读(63)  评论(0编辑  收藏  举报