package thread;
import java.util.concurrent.CountDownLatch;
public class CountDownLatchTest {
public static int i = 0;
public static CountDownLatch c = new CountDownLatch(100);//这里的数字,开启几个线程就写几
public synchronized static void add(){ //注意,如果不加上synchronized,由于并发写入,结果会小于100
i++;
// 每当一个任务线程执行完毕,就将计数器减1,直到线程数为0 CountDownLatch.await()将被唤醒
// 也就是主线程需要等待多个子线程执行完毕,之后再继续执行
c.countDown();
}
public static void main(String[] args) throws Exception{
for(int i =0 ; i < 100; i++){
//开启线程
new Thread(new Runnable() {
public void run() {
try {
CountDownLatchTest.add();
}catch (Exception e){
e.printStackTrace();
}
}
}).start();
}
c.await();//主线程等待子线程执行输出
System.out.println(i);
}
}