溫馨提示×

CountDownLatch的理解和使用

小億
71
2024-01-10 16:43:06
欄目: 編程語言

CountDownLatch是Java中的一個并發(fā)工具類,用于實現(xiàn)線程等待的功能。它可以讓一個或多個線程等待其他線程的操作完成后再繼續(xù)執(zhí)行。

CountDownLatch使用一個計數(shù)器來實現(xiàn)等待。計數(shù)器的初始值可以設(shè)置為一個正整數(shù),當一個線程執(zhí)行完自己的任務(wù)后,計數(shù)器的值減1。當計數(shù)器的值變?yōu)?時,所有等待的線程將被釋放,可以繼續(xù)執(zhí)行。

CountDownLatch的主要方法包括:

  • CountDownLatch(int count):構(gòu)造方法,設(shè)置計數(shù)器的初始值。
  • void await():使當前線程等待,直到計數(shù)器的值變?yōu)?。
  • void countDown():計數(shù)器的值減1。

下面是一個使用CountDownLatch的示例:

import java.util.concurrent.CountDownLatch;

public class CountDownLatchExample {
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch latch = new CountDownLatch(3);  // 設(shè)置計數(shù)器的初始值為3

        Worker worker1 = new Worker(latch, "Worker1");
        Worker worker2 = new Worker(latch, "Worker2");
        Worker worker3 = new Worker(latch, "Worker3");

        worker1.start();
        worker2.start();
        worker3.start();

        latch.await();  // 等待所有線程執(zhí)行完畢

        System.out.println("All workers have finished their tasks.");
    }
}

class Worker extends Thread {
    private CountDownLatch latch;

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

    public void run() {
        try {
            Thread.sleep(1000);  // 模擬任務(wù)執(zhí)行時間
            System.out.println(getName() + " has finished its task.");
            latch.countDown();  // 計數(shù)器的值減1
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

在上面的示例中,我們創(chuàng)建了一個CountDownLatch對象,并將其初始值設(shè)置為3。然后創(chuàng)建了三個Worker線程,并讓它們執(zhí)行任務(wù)。每個Worker線程執(zhí)行完任務(wù)后,都會調(diào)用countDown()方法將計數(shù)器的值減1。主線程調(diào)用await()方法等待計數(shù)器的值變?yōu)?,即所有Worker線程都執(zhí)行完任務(wù)后,主線程才會繼續(xù)執(zhí)行。

注意:CountDownLatch的計數(shù)器是一次性的,一旦計數(shù)器的值變?yōu)?,就無法重置為其他值。如果需要多次使用計數(shù)器,可以考慮使用CyclicBarrier類。

0