[Java]CountDownLatch

转自: https://www.geeksforgeeks.org/countdownlatch-in-java/

 

CountDownLatch is used to make sure that a task waits for other threads before it starts. To understand its application, let us consider a server where the main task can only start when all the required services have started.

Working of CountDownLatch:
When we create an object of CountDownLatch, we specify the number of threads it should wait for, all such thread are required to do count down by calling CountDownLatch.countDown() once they are completed or ready to the job. As soon as count reaches zero, the waiting task starts running.

Example of CountDownLatch in JAVA:

// Java Program to demonstrate how 
// to use CountDownLatch, Its used 
// when a thread needs to wait for other 
// threads before starting its work. 
import java.util.concurrent.CountDownLatch; 

public class CountDownLatchDemo 
{ 
	public static void main(String args[]) 
				throws InterruptedException 
	{ 
		// Let us create task that is going to 
		// wait for four threads before it starts 
		CountDownLatch latch = new CountDownLatch(4); 

		// Let us create four worker 
		// threads and start them. 
		Worker first = new Worker(1000, latch, 
								"WORKER-1"); 
		Worker second = new Worker(2000, latch, 
								"WORKER-2"); 
		Worker third = new Worker(3000, latch, 
								"WORKER-3"); 
		Worker fourth = new Worker(4000, latch, 
								"WORKER-4"); 
		first.start(); 
		second.start(); 
		third.start(); 
		fourth.start(); 

		// The main task waits for four threads 
		latch.await(); 

		// Main thread has started 
		System.out.println(Thread.currentThread().getName() + 
						" has finished"); 
	} 
} 

// A class to represent threads for which 
// the main thread waits. 
class Worker extends Thread 
{ 
	private int delay; 
	private CountDownLatch latch; 

	public Worker(int delay, CountDownLatch latch, 
									String name) 
	{ 
		super(name); 
		this.delay = delay; 
		this.latch = latch; 
	} 

	@Override
	public void run() 
	{ 
		try
		{ 
			Thread.sleep(delay); 
			latch.countDown(); 
			System.out.println(Thread.currentThread().getName() 
							+ " finished"); 
		} 
		catch (InterruptedException e) 
		{ 
			e.printStackTrace(); 
		} 
	} 
} 

Output:

WORKER-1 finished
WORKER-2 finished
WORKER-3 finished
WORKER-4 finished
main has finished

 

Facts about CountDownLatch:

  1. Creating an object of CountDownLatch by passing an int to its constructor (the count), is actually number of invited parties (threads) for an event.
  2. The thread, which is dependent on other threads to start processing, waits on until every other thread has called count down. All threads, which are waiting on await() proceed together once count down reaches to zero.
  3. countDown() method decrements the count and await() method blocks until count == 0

 

也可以参考: https://www.jianshu.com/p/965ffb474d89

 

https://upload-images.jianshu.io/upload_images/8054235-260495a9e97d7325?imageMogr2/auto-orient/strip|imageView2/2/w/864

public class CountDownLatchTest {
    public static void main(String[] args) throws Exception{

        /*创建CountDownLatch实例,计数器的值初始化为3*/
        final CountDownLatch downLatch = new CountDownLatch(3);

        /*创建三个线程,每个线程等待1s,表示执行比较耗时的任务*/
        for(int i = 0;i < 3;i++){
            final int num = i;
            new Thread(new Runnable() {
                public void run() {
                    try {
                        Thread.sleep(1000);

                    }catch (InterruptedException e){
                        e.printStackTrace();

                    }

                    System.out.println(String.format("thread %d has finished",num));

                    /*任务完成后调用CountDownLatch的countDown()方法*/
                    downLatch.countDown();
                }
            }).start();
        }

        /*主线程调用await()方法,等到其他三个线程执行完后才继续执行*/
        downLatch.await();

        System.out.print("all threads have finished,main thread will continue run");
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值