多线程之闭锁CountDownLatch

版权声明:不短不长八字刚好@wzy https://blog.csdn.net/qq_38089964/article/details/81629299

闭锁可以理解为要达到一组需要完成的步骤之后才能让所有线程继续往下走;就像一个学校大门,所有的学生都想放学回家都堵在门口,这时候必须等到保安做完他的事才能放行(比如说上厕所),完事之后,一开大门,所有的学生(线程)才能通过大门,继续走。

这里写了一个很好理解的一个demo:

package cn.wzy.regextest;


import java.util.concurrent.CountDownLatch;

/**
 * Create by Wzy
 * on 2018/8/3 9:42
 * 不短不长八字刚好
 */
public class Main {

    public static void main(String[] args) throws InterruptedException {
        final CountDownLatch start = new CountDownLatch(1);
        for (int i = 0; i < 5; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        System.out.println("线程:" + Thread.currentThread().getId() + " ready..");
                        start.await();
                        System.out.println("线程:" + Thread.currentThread().getId() + " complete..");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
        System.out.println("我说开始才开始..  start");
        Thread.sleep(5000);
        System.out.println("start!");
        start.countDown();
    }
}

结果:等到说开始的之后,所有线程才能继续往下。

猜你喜欢

转载自blog.csdn.net/qq_38089964/article/details/81629299