CountDownLatch 同步辅助计时类,主要包含:
一个带计时参数的构造函数:CountDownLatch(int count);
计数减1方法:void countDown();
阻塞当前线程直到所有线程完成即计数器值为0:await() 或 await(long timeout, TimeUnit unit) 使用带参方法时,当计数器值为0或者耗时完时结束
示例:5个员工完成工作耗时,coolPoolSize分配决定了执行时间是否一致
public class CountDownLatchDemo {
private static final String FORMAT = "yy-MM-dd HH:mm:ss";
private static final Random RANDOM = new Random();
public static String getFormat(Date date) {
SimpleDateFormat sdf = new SimpleDateFormat(FORMAT);
return sdf.format(date);
}
public static void main(String[] args) throws Exception {
int selfCompleteNum = 1;
int allCompleteNum = 5;
CountDownLatch selfDownLatch = new CountDownLatch(selfCompleteNum);
CountDownLatch countDownLatch = new CountDownLatch(allCompleteNum);
//添加工人
Worker[] workers = new Worker[allCompleteNum];
for (int i = 0; i < allCompleteNum; i++) {
workers[i] = new Worker("emp" + i, selfDownLatch, countDownLatch);
}
//设置线程池,不适用Executors创建是为了规避资源耗尽风险
ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
.setNameFormat("worker-pool-%d").build();
//coolPoolSize分配
ExecutorService pool = new ThreadPoolExecutor(5, 20, 0L,
TimeUnit.MILLISECONDS, new LinkedBlockingDeque<Runnable>(1024),
namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());
//分配线程
for (Worker worker : workers) {
pool.execute(worker);
}
//开始工作
selfDownLatch.countDown();
//完成工作
countDownLatch.await();
pool.shutdown();
System.out.println("均完成后的时间:" + getFormat(new Date()));
}
private static class Worker extends Thread {
private String workName;
private CountDownLatch selfLatch;
private CountDownLatch latch;
public Worker(String workName, CountDownLatch selfLatch, CountDownLatch latch) {
this.workName = workName;
this.selfLatch = selfLatch;
this.latch = latch;
}
@Override
public void run() {
System.out.println("Worker " + workName + " do work begin at " + getFormat(new Date()));
doWork();
System.out.println("Worker " + workName + " do work complete at " + getFormat(new Date()));
}
private void doWork() {
try {
selfLatch.await();
Thread.sleep(RANDOM.nextInt(3) * 1000 + 1000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
latch.countDown();
System.out.println("Worker " + workName + " CountDownLatch count " + latch.getCount());
}
}
}
}
返回结果如下:
Worker emp1 do work begin at 17-06-15 16:42:51
Worker emp3 do work begin at 17-06-15 16:42:51
Worker emp2 do work begin at 17-06-15 16:42:51
Worker emp4 do work begin at 17-06-15 16:42:51
Worker emp0 do work begin at 17-06-15 16:42:51
Worker emp0 CountDownLatch count 4
Worker emp0 do work complete at 17-06-15 16:42:52
Worker emp2 CountDownLatch count 2
Worker emp3 CountDownLatch count 2
Worker emp2 do work complete at 17-06-15 16:42:53
Worker emp3 do work complete at 17-06-15 16:42:53
Worker emp1 CountDownLatch count 0
Worker emp4 CountDownLatch count 0
Worker emp1 do work complete at 17-06-15 16:42:54
Worker emp4 do work complete at 17-06-15 16:42:54
均完成后的时间:17-06-15 16:42:54