CountDownLatch是Java中的一个同步辅助类,它允许一个或多个线程等待直到一组操作完成
import java.util.concurrent.CountDownLatch;
int numberOfThreads = 5; // 假设有5个子线程需要等待
CountDownLatch latch = new CountDownLatch(numberOfThreads);
latch.countDown()
方法来减少计数器值:for (int i = 0; i < numberOfThreads; i++) {
new Thread(new Runnable() {
@Override
public void run() {
try {
// 执行任务
System.out.println(Thread.currentThread().getName() + " is working.");
Thread.sleep(1000); // 假设每个子线程需要1秒钟来完成任务
// 任务完成后,减少计数器值
latch.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
latch.await()
方法来阻塞主线程,直到计数器值变为0:try {
latch.await(); // 主线程将阻塞,直到所有子线程完成任务
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("All threads have finished their tasks.");
将以上代码整合到一个完整的示例中:
import java.util.concurrent.CountDownLatch;
public class CountDownLatchExample {
public static void main(String[] args) {
int numberOfThreads = 5; // 假设有5个子线程需要等待
CountDownLatch latch = new CountDownLatch(numberOfThreads);
for (int i = 0; i < numberOfThreads; i++) {
new Thread(new Runnable() {
@Override
public void run() {
try {
// 执行任务
System.out.println(Thread.currentThread().getName() + " is working.");
Thread.sleep(1000); // 假设每个子线程需要1秒钟来完成任务
// 任务完成后,减少计数器值
latch.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
try {
latch.await(); // 主线程将阻塞,直到所有子线程完成任务
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("All threads have finished their tasks.");
}
}
运行这个示例,你会看到主线程在所有子线程完成任务之前阻塞,然后输出"All threads have finished their tasks."。