CountDownLatch的一个有用特性是,它不要求调用countDown方法的线程等到计数到达零时才继续,而在所有线程都能通过之前,它只是阻止任何线程继续通过一个 await。
以下是一个简单的例子
演示了启动5个线程,等到所有线程执行完毕之后,打印出最后结果
package com.lala.shop;
import java.time.Duration;
import java.time.Instant;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
public class CountDownLatchDemo
{
/**
* 启动size个线程,等到所有线程执行完毕之后,打印出最后结果
* @param size
*/
public void demo(final int size)
{
CountDownLatch cdl = new CountDownLatch(size);
Instant start = Instant.now();
for(int i=1;i<=size;i++)
{
new Thread(() -> {
try
{
long time = new Long(new Random().nextInt(10));
TimeUnit.SECONDS.sleep(time);
System.out.println(Thread.currentThread().getName() + " sleep " + time + " then finish ...");
cdl.countDown();
} catch (InterruptedException e)
{
e.printStackTrace();
}
}).start();
}
try
{
cdl.await();
} catch (InterruptedException e)
{
e.printStackTrace();
}
Instant end = Instant.now();
Duration time = Duration.between(start, end);
long seconds = time.getSeconds();//秒表示
System.out.println("finish this task ... spend time " + seconds + " seconds");
}
public static void main(String[] args)
{
new CountDownLatchDemo().demo(5);
}
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文:http://blog.csdn.net/mn960mn/article/details/46655651