countDownLatch
import java.util.concurrent.CountDownLatch;
/**
* CountDownLatch:闭锁,在完成某些运算时,只有其他所有线程的运算
* 全部完成,当前运算才继续执行
*/
public class CountDownLatchTest {
public static void main(String[] args) {
//该CountDownLatch类的参数表示线程的数量个数
final CountDownLatch latch = new CountDownLatch(5);
LatchDemo ld = new LatchDemo(latch);
long start = System.currentTimeMillis();
for (int i = 0; i < 5; i++) {
new Thread(ld).start();
}
try {
//调用await()方法的线程会被挂起,它会等待直到new CountDownLatch(5)为0才继续执行
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
long end = System.currentTimeMillis();
System.out.println("耗费时间:"+ (end - 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 <5000 ; i++) {
if (i % 2 == 0){
System.out.println(i);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
//new CountDownLatch(5)线程的数量自减一
latch.countDown();
}
}
}
}