在Java中,CountDownLatch類可以用來實現倒計時功能。CountDownLatch是一個同步輔助類,它允許一個或多個線程等待其他線程完成操作。
CountDownLatch的用法如下:
示例代碼如下:
import java.util.concurrent.CountDownLatch;
public class CountdownExample {
public static void main(String[] args) {
CountDownLatch latch = new CountDownLatch(3);
new Thread(new Worker(latch, "Worker1")).start();
new Thread(new Worker(latch, "Worker2")).start();
new Thread(new Worker(latch, "Worker3")).start();
try {
latch.await();
System.out.println("All workers have completed their tasks");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
static class Worker implements Runnable {
private CountDownLatch latch;
private String name;
Worker(CountDownLatch latch, String name) {
this.latch = latch;
this.name = name;
}
@Override
public void run() {
System.out.println(name + " is working");
latch.countDown();
}
}
}
在上面的示例中,創建了一個CountDownLatch對象并指定初始值為3。然后創建了3個Worker線程,每個線程在執行時都會調用countDown()方法來減少計數器的值。最后在主線程中調用await()方法等待計數器歸零,當所有Worker線程都完成任務后,主線程將被喚醒并輸出提示信息。