分析
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 ( ) ;
}
}
}