CountDownLatch 的使用方法

CountDownLatch是Java并发工具类,用于同步线程,通过计数器实现线程等待。构造函数接收一个整数参数,表示计数值。线程调用countDown()方法减少计数,当计数为0时,await()调用的线程将解除阻塞。示例展示了如何使用CountDownLatch让三个线程执行完毕后,主线程继续执行。
摘要由CSDN通过智能技术生成

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() 方法来阻塞,直到门闩被释放。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值