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()方法递减count和await()方法块,直到count == 0
 
转载请保留页面地址:https://www.breakyizhan.com/java/4972.html
扫描二维码添加微信 
  • ,每次淘宝领取淘宝优惠券,淘宝购物更优惠。现在添加微信,还可以领取机械键盘50元优惠券!添加微信后回复机械键盘即可领取!
    支持我们,就用微信淘宝!