CountDownLatch 的使用方法

A CountDownLatch is a concurrent utility class in Java that provides a mechanism to synchronize threads by allowing one or more threads to wait for a set of operations performed by other threads to complete. It is a kind of latch that allows a thread to wait until a set of operations performed by other threads completes.

The CountDownLatch class has a single constructor that takes an integer value as an argument. This integer value specifies the number of threads that must invoke the countDown() method before the latch is released and the waiting threads are allowed to proceed. The threads that are waiting for the latch to be released can call the await() method to block until the latch is released.

Here is an example of how to use a CountDownLatch:

import java.util.concurrent.CountDownLatch;

public class Main {
  public static void main(String[] args) {
    CountDownLatch latch = new CountDownLatch(3);

    new Thread(() -> {
      System.out.println("Thread 1 is running");
      latch.countDown();
    }).start();

    new Thread(() -> {
      System.out.println("Thread 2 is running");
      latch.countDown();
    }).start();

    new Thread(() -> {
      System.out.println("Thread 3 is running");
      latch.countDown();
    }).start();

    try {
      latch.await();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

    System.out.println("All threads have finished running");
  }
}

This code creates a CountDownLatch with a count of 3, and then creates three threads that each call the countDown() method on the latch. The main thread then calls the await() method on the latch, which blocks until the count reaches 0. When the count reaches 0, the main thread is allowed to proceed and prints a message indicating that all threads have finished running.

总结:
CountDownLatch 是 Java 中的一个并发工具类,它提供了一种机制,可以通过允许一个或多个线程等待其他线程完成的一组操作来同步线程。它是一种门闩,允许线程等待其他线程完成的操作集合完成之前阻塞。
CountDownLatch 类有一个构造函数,可以接受一个整数值作为参数。该整数值指定在释放门闩并允许等待的线程继续之前必须调用 countDown() 方法的线程数。等待门闩被释放的线程可以调用 await() 方法来阻塞,直到门闩被释放。

猜你喜欢

转载自blog.csdn.net/u013168615/article/details/128406575