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."。