Thread synchronization class: CountDownLatch

CountDownLatch: patriarch

Construction method:

// count为门阀数,必须大于0,否则抛出异常
CountDownLatch countDownLatch = new CountDownLatch(int count);

For example: when the sprint race at the Games, there are eight players and a referee, the referee as the main thread, only eight athletes completed the race, after the result and in order to make statistics, finished behind (call await method), each athlete to reach the terminal, will call (countdown method), minus the number of a powerful family, when all eight athletes to the finish line, the number of gate valve is zero, then the referee can continue down the
main method:
countDownLatch.awati () method:
this method is called a thread will wait until the time passed in the constructor count reaches zero, you can proceed down;
countDownLatch.countdown () method:
each call, the constructor incoming number count will subtract 1

scenes to be used:

Almost all threads work together at the same time:
ideas: setting a powerful family, the other threads invoked await wait and let the main function to open the valve (call countdown method), count reaches zero, all threads will work with
the code:
gate valve categories: providing method requires waiting call, a class can also be written

class JymCountDownLatch {

    // 门阀类
    private CountDownLatch countDownLatch;

    public JymCountDownLatch(CountDownLatch countDownLatch) {
        this.countDownLatch = countDownLatch;
    }

    public void excu(){
        try {
            // 被上锁的线程,直到 CountDownLatch 的 count 为 0 才继续执行
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Thread class:

class JymCountDownLatchThread implements Runnable{

    private JymCountDownLatch jymCountDownLatch;

    public JymCountDownLatchThread(JymCountDownLatch jymCountDownLatch) {
        this.jymCountDownLatch = jymCountDownLatch;
    }

    public void run() {
        jymCountDownLatch.excu();
        System.out.println(Thread.currentThread().getName()+":"+System.currentTimeMillis());
    }
}

Test Class Code:

    public static void main(String[] args) {
        CountDownLatch countDownLatch = new CountDownLatch(1);
        JymCountDownLatch jymCountDownLatch = new JymCountDownLatch(countDownLatch);
        JymCountDownLatchThread jymCountDownLatchThread = new JymCountDownLatchThread(jymCountDownLatch);
        for (int i = 0;i<5;i++){
            new Thread(jymCountDownLatchThread).start();
        }
        // 打开阀门
        countDownLatch.countDown();
        System.out.println("QWQ");
    }

result:
Here Insert Picture Description

Lack of study time, too shallow knowledge, that's wrong, please forgive me.

There are 10 kinds of people in the world, one is to understand binary, one is do not understand binary.

Published 71 original articles · won praise 54 · views 420 000 +

Guess you like

Origin blog.csdn.net/weixin_43326401/article/details/104121291