Java 5.0 在 java.util.concurrent 包中提供了多种并发容器类来改进同步容器 的性能。
测出5个线程同时打印出5000以内的偶数,一共用耗时多少 ?
package com.gf.demo;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.concurrent.CountDownLatch;
public class TestCountDownLatch {
public static void main(String args[]){
CountDownLatch latch = new CountDownLatch( 5 );
LatchDemo ld = new LatchDemo(latch);
Instant start = Instant.now();
for (int i = 0 ; i < 5 ; i++) {
new Thread( ld ).start();
}
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
long between = ChronoUnit.MILLIS.between( start , Instant.now() );
System.out.println("耗时 = " + between);
}
}
class LatchDemo implements Runnable {
private CountDownLatch countDownLatch;
public LatchDemo (CountDownLatch countDownLatch) {
this.countDownLatch = countDownLatch;
}
@Override
public void run() {
try {
for (int i = 0 ; i < 50000 ; i++) {
if (i % 2 == 0) {
System.out.println(i);
}
}
} finally {
countDownLatch.countDown();
}
}
}
上面的实例,计数器的值为5,main 线程执行计算时间的任务调用 CountDownLatch 的 await()方法 ,进入等待;5个线程每次执行完任务都会执行CountDownLatch 的countDown() 方法,对计数器的值进行减 1,计数器的值变为0时,就表示5个线程均已经完成了任务,然后就可以恢复等待的main线程继续执行了。
评论