Java study notes-use of countDown() in thread

1. Explanation

Wait for other threads to finish processing before continuing the current thread. For example, if you want to execute the B thread, there is an A thread in front, and the A thread must be executed before the B thread can be executed.

A thread waits for n threads to finish executing before starting to run. The counter of CountDownLatch is initialized to n new CountDownLatch(n), every time a task thread is executed, the counter is decremented by 1 countdownlatch.countDown(), when the value of the counter becomes 0, the thread of await() on CountDownLatch is Will be awakened. A typical application scenario is that when starting a service, the main thread needs to wait for multiple components to be loaded before continuing.
 

2. Use

/**第一步:设置线程A的运行次数为2/
CountDownLatch latch = new CountDownLatch(2); 
/**第二步:递减锁存器的计数,如果计数到达零,则释放所有等待的线程**/
latch.countDown();  
/**第三步:使当前线程在锁存器倒计数至零之前一直等待,除非线程被中断 
 * 如果当前的计数为零,则此方法立即返回 **/
latch.await();  

 

The two main methods of CountDownLatch are one is CountDownLatch.await() to block the current thread, and the other is CountDownLatch.countDown() to decrement the counter by one from the current thread.

 

3. Examples

public class Test {

    public static void main(String[] args){
        final int count = 10; // 计数次数
        final CountDownLatch latch = new CountDownLatch(count);
        for (int i = 0; i < count; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        // do anything
                        System.out.println("线程"
                            + Thread.currentThread().getId());
                    } catch (Throwable e) {
                        // whatever
                    } finally {
                        // 很关键, 无论上面程序是否异常必须执行countDown,否则await无法释放
                        latch.countDown();
                    }
                }
            }).start();
        }
        try {
            // 10个线程countDown()都执行之后才会释放当前线程,程序才能继续往后执行
            latch.await();
        } catch (InterruptedException e) {
            // whatever
        }
        System.out.println("Finish");
    }


}

 

Guess you like

Origin blog.csdn.net/mumuwang1234/article/details/115122164
Recommended