TestCountDownLatch.java package com.min.juc;import java.util.concurrent.CountDownLatch;/** * CountDownLatch,一个同步辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个或多个线程一直等待。
package com.min.juc;
import java.util.concurrent.CountDownLatch;
/**
* CountDownLatch,一个同步辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个或多个线程一直等待。
* 构造方法参数指定了计数的次数 countDown方法,当前线程调用此方法,则计数减一 。awaint方法,调用此方法会一直阻塞当前线程,直到计时器的值为0
* @author min
*/
public class TestCountDownLatch {
public static void main(String[] args) {
final CountDownLatch latch = new CountDownLatch(10);
LatchDemo ld = new LatchDemo(latch);
long start = System.currentTimeMillis();
for(int i=0;i<10;i++) {
new Thread(ld).start();
}
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("消耗时间:"+String.valueOf(System.currentTimeMillis()-start));
}
}
class LatchDemo implements Runnable{
private CountDownLatch latch;
public LatchDemo(CountDownLatch latch) {
this.latch = latch;
}
@Override
public void run() {
synchronized (this) {
try {
for (int i = 0; i < 50000; i++) {
if (i % 2 == 0) {
System.out.println(i);
}
}
} finally {
latch.countDown();
}
}
}
}
