📜  Java中的CountDownLatch

📅  最后修改于: 2022-05-13 01:55:17.499000             🧑  作者: Mango

Java中的CountDownLatch

CountDownLatch 用于确保任务在开始之前等待其他线程。为了理解它的应用,让我们考虑一个服务器,它的主要任务只有在所有必需的服务都启动后才能启动。

CountDownLatch 的工作:
当我们创建一个 CountDownLatch 的对象时,我们指定它应该等待的线程数,一旦它们完成或准备好工作,所有这些线程都需要通过调用 CountDownLatch.countDown() 来进行倒计时。一旦计数达到零,等待任务开始运行。

Java中的 CountDownLatch 示例:

// 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();
        }
    }
}

输出:

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

关于 CountDownLatch 的事实:

  1. 通过将 int 传递给其构造函数(计数)来创建 CountDownLatch 对象,实际上是事件的受邀方(线程)的数量。
  2. 依赖于其他线程开始处理的线程一直等待,直到所有其他线程都调用倒计时。一旦倒计时达到零,所有等待 await() 的线程都会一起进行。
  3. countDown() 方法递减计数,await() 方法阻塞直到 count == 0