CountDownLatch含义:必须等待一部分任务执行完成,才能执行下面的业务。
public class MyCountDownLatch {
private final int total;
private int count = 0 ;
public MyCountDownLatch ( int total) { this . total = total;
}
public synchronized void countDown ( ) {
count ++ ;
this . notifyAll ( ) ;
}
public synchronized void await ( ) {
while ( count != total) {
try {
System. out. println ( "waiting......." ) ;
this . wait ( ) ;
} catch ( InterruptedException e) {
break ;
}
}
}
}
public class JDKCountDownLatchDemo {
private final static Random random = new Random ( System. currentTimeMillis ( ) ) ;
public static void main ( String[ ] args) throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch ( 5 ) ;
AtomicInteger counter = new AtomicInteger ( 0 ) ;
IntStream. rangeClosed ( 1 , 5 ) . forEach ( item - > {
new Thread ( ( ) - > {
System. out. println ( Thread. currentThread ( ) . getName ( ) + " is working " + counter. getAndIncrement ( ) ) ;
try {
Thread. sleep ( random. nextInt ( 1000 ) ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
countDownLatch. countDown ( ) ;
} , String. valueOf ( item) ) . start ( ) ;
} ) ;
countDownLatch. await ( ) ;
System. out. println ( "工作执行完成" ) ;
}
}