我的要求是在kickstarting從屬作業之前等待兩個線程完成執行。有沒有比使用CountDownLatch等待兩個線程完成任務的更好方法?
爲了做到這一點,我可以創造一個CountDownLatch
和Waiter
Thread
將等待CountDownLatch
變爲零。一個約束是我不能使用主線程等待兩個線程完成。主線程繼續執行其他任務。
這個東西確實有效。不過,我覺得這個解決方案比一個堅實的設計。
我的問題有以下幾點:
- 什麼是當前的做法明顯的缺陷?例如虛假信號
- 您會推薦什麼設計?
我當前的代碼:
class Waiter implements Runnable {
private CountDownLatch latch;
Waiter (CountDownLatch latch){
this.latch = latch;
}
@Override
public void run() {
System.out.println("Waiter Started running..." + latch.getCount());
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Waiter ready to trigger Next Job!");
}
}
class Processor implements Runnable {
private CountDownLatch latch;
Processor (CountDownLatch latch){
this.latch = latch;
}
@Override
public void run() {
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
latch.countDown();
}
}
public class CountDownLatchDemo {
public static void main (String[] args) throws InterruptedException{
CountDownLatch latch = new CountDownLatch(2);
ExecutorService executor = Executors.newFixedThreadPool(2);
for (int i=0; i< 2; i++){
executor.submit(new Processor(latch));
}
ExecutorService waitExecutor = Executors.newFixedThreadPool(2);
waitExecutor.submit(new Waiter(latch));
Thread.sleep(3000);
executor.shutdown();
waitExecutor.shutdown();
System.out.println("Keep doing other things! Sleep here is just for help you run this code for test!");
}
}
這對我來說很好。較低級別的替代方法是在兩個線程上調用join()。 –
加入將需要在我想避免的主線程中,因爲我將需要線程繼續做其他的東西。 – Learner
使用CountDownLatch在這種情況下是一個完全有效的方法,不需要使它更復雜 –