分析
- Count-Down設計模式其實也叫做Latch(閥門)設計模式。
- 當若干個線程併發執行完某個特定的任務,然後
等到所有的子任務都執行結束之後再統一彙總。
JDK包中的實現
public class JDKCountDown {
private static final Random RANDOM = new Random(System.currentTimeMillis());
public static void main(String[] args) throws InterruptedException {
final CountDownLatch latch = new CountDownLatch(5);
System.out.println("準備多線程處理任務....");
IntStream.rangeClosed(1,5).forEach(i->
new Thread(()->{
System.out.println(Thread.currentThread().getName() + " is working....");
try {
Thread.sleep(RANDOM.nextInt(1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
latch.countDown();
},String.valueOf(i)).start()
);
latch.await();
System.out.println("多線程任務全部結束,進行第二階段.....");
}
}
模擬CountDown
public class CountDown {
private final int total;
private int counter ;
public CountDown(int total) {
this.total = total;
counter = 0;
}
public synchronized void down(){
this.counter++;
this.notifyAll();
}
public synchronized void await() throws InterruptedException {
while (counter!=total){
this.wait();
}
}
}