CountDownLatch
private static void countDownLatch() throws InterruptedException {
int length = 100;
CountDownLatch latch = new CountDownLatch(length);
Long t1 = System.nanoTime();
List<Integer> results = new ArrayList<>();
for (int index = 0; index < length; index++) {
final int threadIndex = index;
Thread thread = new Thread(() -> {
System.out.println("start thread - " + threadIndex);
Double random = -1.0;
try {
Thread.sleep(1 * 1000);
random = (100 * Math.random());
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("stop thread - " + threadIndex + " random = " + random.intValue());
results.add(random.intValue());
latch.countDown();
});
thread.start();
}
// 注意:CountDownLatch要加上这段才生效,原因见下面文字描述
latch.await();
System.out.println("跑完了...");
Long t2 = System.nanoTime();
System.out.println(results);
System.out.println("time = " + (t2 - t1));
}
CountDownLatch的构造函数接受一个int类型的参数作为计数器,如果你想等待N个节点(N个Thread 如上述示例 ),这里就传入N
CountDownLatch.countDown()
调用CountDownLatch.countDown() ,N就会减1
CountDownLatch.wait()
CountDownLatch.wait()会阻塞当前线程,直到N变成零
当某个线程处理的特别慢时,如果不需要主线程一直等待下去,可以使用另外一个重载的wait(long time,TimeUnit unit),这个方法等待指定时间后就不再阻塞线程了
链接:https://www.jianshu.com/p/00d0fcdeb7df
来源:oschina
链接:https://my.oschina.net/u/937111/blog/4728914