CountDownLatch同步辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个或多个线程一直等待
countDown()当前线程调此方法,则计数减一(建议放在finally里执行)
await() 调用此方法一直阻塞当前线程 直到计数器的值为0;
package singleton;
import java.util.concurrent.CountDownLatch;
/**
* 因为是多个线程 mian同时开启了十个线程 ,如果没等那十个线程执行完毕,main就结束了,那么
* 测试的耗时将不准确,这里使用了CountDownLatch辅助类,计数器次数和线程数设为相同 每当一个线程执行完毕
* cdl.countDown()调用此方法计数器减一 cdl.await();// main线程阻塞,直到计数器变为0,阻塞消除
*
* @author re
*
*/
public class CountDownLatchTest {
public static void main(String[] args) throws InterruptedException {
long stattime = System.currentTimeMillis();
int ThreadCount = 10;
final CountDownLatch cdl = new CountDownLatch(ThreadCount);
for (int i = 0; i < 10; i++) {
new Thread(new Runnable() {
@Override
public void run() {
for (int j = 0; j < 1000; j++) {
System.out.println(Thread.currentThread().getName() + ":" + j);
}
cdl.countDown();// 到此一个线程执行完比,ThreadCount-1
}
}).start();
}
cdl.await();// main线程阻塞,直到计数器变为0,阻塞消除
long end = System.currentTimeMillis();
System.out.println("耗时" + (end - stattime));
}
}