在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线程都完成任务后,主线程将被唤醒并输出提示信息。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读:java中countdown的作用是什么