Java中CountDownLatch工具类代码理解
时间: 2023-10-13 19:10:03 浏览: 93
CountDownLatch是Java中一个非常有用的同步工具类,它可以让一个或多个线程等待其他线程完成它们的操作后再执行。在Java中,CountDownLatch类是通过一个计数器来实现的,计数器的初始值可以设置为任何整数。当某个线程调用CountDownLatch的await()方法时,它会阻塞等待计数器的值变为0;而其他线程执行完它们的操作后会通过调用CountDownLatch的countDown()方法来减少计数器的值。当计数器的值变为0时,await()方法将返回,线程得以继续执行。
下面是一个使用CountDownLatch的示例代码:
```java
import java.util.concurrent.CountDownLatch;
public class CountDownLatchExample {
public static void main(String[] args) throws InterruptedException {
int numThreads = 5;
CountDownLatch latch = new CountDownLatch(numThreads);
for (int i = 0; i < numThreads; i++) {
new Thread(new Worker(i, latch)).start();
}
latch.await();
System.out.println("All threads have finished!");
}
static class Worker implements Runnable {
private int id;
private CountDownLatch latch;
public Worker(int id, CountDownLatch latch) {
this.id = id;
this.latch = latch;
}
public void run() {
System.out.println("Worker " + id + " is working...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Worker " + id + " has finished.");
latch.countDown();
}
}
}
```
在这个例子中,我们创建了5个线程,并用CountDownLatch来等待它们全部执行完毕。每个线程都会休眠1秒钟,然后调用countDown()方法来减少计数器的值,最终当所有线程都执行完毕时,await()方法返回,打印出"All threads have finished!"。
阅读全文