CountDownLatch是一个同步工具类,它允许一个或多个线程一直等待,直到其他线程的操作执行完后再执行。
其实用Thread的join方法也是可以等到线程执行完之后,再去执行后面的代码。
CountDownLatch实现线程等待,直到子线程执行完毕,主线程才往下执行。
public class CountDownTest {
public static void main(String[] args){
final CountDownLatch latch = new CountDownLatch(5);
IntStream.range(1,6).forEach(i->new Thread(()->{
System.out.println(Thread.currentThread().getName() + " is working !!!");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
latch.countDown();
},String.valueOf(i)).start());
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("the second phase start");
System.out.println("working ");
System.out.println("FINISHED");
}
}
输出结果:
自定义CountDownLatch
代码:
public class CustomCountDown {
// 通过一个计数器,来统计完成的线程个数,如果小于总数就让主线程等待
private int total ;
public CustomCountDown(int total) {
this.total = total;
}
public void countDown(){
synchronized (this){
total --;
}
}
public void await() throws InterruptedException {
synchronized (this){
while (total > 0){
wait();
}
notifyAll();
}
}
}
调用逻辑跟JDK自带的一样使用,输出结果也是一样的。
下面是join的代码,其输出结果是一样的:
public class JoinTest {
public static void main(String[] args){
IntStream.range(1,6).forEach(i->{
Thread thread = new Thread(()->{
System.out.println(Thread.currentThread().getName() + " is working !!!");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
},String.valueOf(i));
thread.start();
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
System.out.println("the second phase start");
System.out.println("working ");
System.out.println("FINISHED");
}
}