CountDownLatch 是 Java 并发包 java.util.concurrent 中的一个同步工具类,它允许一个或多个线程等待其他线程完成操作。CountDownLatch 通过一个计数器来实现,该计数器的初始值为线程的数量。每当一个线程完成了任务,计数器的值就会减一。当计数器的值变为0时,表示所有线程都已完成任务,然后在闭锁上等待的线程就可以恢复执行任务。
以下是 CountDownLatch 的一些基本用法:
CountDownLatch 实例,并指定计数器的初始值。int numberOfThreads = 5;
CountDownLatch latch = new CountDownLatch(numberOfThreads);
countDown() 方法来减少计数器的值。Thread thread = new Thread(() -> {
try {
// 执行任务
System.out.println(Thread.currentThread().getName() + " is running");
Thread.sleep(1000); // 模拟任务执行时间
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
latch.countDown(); // 任务完成后减少计数器
}
});
thread.start();
await() 方法来阻塞线程,直到计数器的值变为0。try {
latch.await(); // 等待所有线程完成任务
System.out.println("All threads have completed their tasks.");
} catch (InterruptedException e) {
e.printStackTrace();
}
完整的示例代码如下:
import java.util.concurrent.CountDownLatch;
public class CountDownLatchExample {
public static void main(String[] args) {
int numberOfThreads = 5;
CountDownLatch latch = new CountDownLatch(numberOfThreads);
for (int i = 0; i < numberOfThreads; i++) {
Thread thread = new Thread(() -> {
try {
// 执行任务
System.out.println(Thread.currentThread().getName() + " is running");
Thread.sleep(1000); // 模拟任务执行时间
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
latch.countDown(); // 任务完成后减少计数器
}
});
thread.start();
}
try {
latch.await(); // 等待所有线程完成任务
System.out.println("All threads have completed their tasks.");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
在这个示例中,我们创建了5个线程,每个线程执行一个简单的任务,并在任务完成后减少计数器的值。主线程调用 await() 方法来等待所有线程完成任务,然后打印一条消息表示所有线程已完成任务。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。