代码演示说明
import java.util.concurrent.CountDownLatch;
public class CountDownLatchDemo {
public static void main(String[] args) {
CountDownLatch cdl = new CountDownLatch(10);
CDLTest cdlTest = new CDLTest(cdl);
long start = System.currentTimeMillis();
for (int i = 0; i < 10; i++) {
new Thread(cdlTest).start();
}
try {
cdl.await();
} catch (InterruptedException e) { }
long end = System.currentTimeMillis();
System.out.println(end-start);
}
}
class CDLTest implements Runnable {
private final CountDownLatch cd;
private int sum = 0;
public CDLTest(CountDownLatch cd) {
this.cd = cd;
}
@Override
public void run() {
synchronized (this) {
try {
for (int i = 0; i < 50000; i++) {
if (i % 10000 == 0) {
try { Thread.sleep(10); } catch (InterruptedException e) { }
}
sum+=i;
}
System.out.println(Thread.currentThread().getName()+" "+sum);
}finally {
sum=0;
cd.countDown();
}
}
}
}