线程等待——CountDownLatch使用
告警性能优化过程中,遇到如下问题:1、 在数据库计算几十万个实体的KPI值的方差;2、 计算结果进行表格化处理。
这里KPI包含多个Counter的数据库函数运算(比如Decode,AVG等函数),方差也是数据库函数运算,性能比较差。
步骤1中每个实体独立计算方差,步骤2需要方差结果协同处理,所以很自然的联想到步骤1分实体多线程处理,步骤2等待步骤1所有线程完成后才开始处理。这里我们使用CountDownLatch进行线程等待,示例代码如下:
package com.coshaho.threadpool; import java.util.concurrent.CountDownLatch; /** * CountDownLatch学习 * @author coshaho */ public class MyCountDownLatch { public static void main(String[] args) throws InterruptedException { // 定义线程等待变量CountDownLatch,此处定义等待3个线程执行完成 CountDownLatch latch = new CountDownLatch(3); // 定义3个线程,并传入线程等待变量 new Thread(new MyCountDownLatch().new MyWork("Thread1",latch)).start(); new Thread(new MyCountDownLatch().new MyWork("Thread2",latch)).start(); new Thread(new MyCountDownLatch().new MyWork("Thread3",latch)).start(); // 等待3个线程执行完成 latch.await(); System.out.println("All works are done."); } /** * 线程任务 * @author coshaho */ private class MyWork implements Runnable { private String workName; private CountDownLatch latch; public MyWork(String workName, CountDownLatch latch) { this.workName = workName; this.latch = latch; } @Override public void run() { try { System.out.println("Thread " + workName + " is running."); Thread.sleep(1000); System.out.println("Thread " + workName + " is stop."); } catch (InterruptedException e) { e.printStackTrace(); } finally { // 线程执行完成,线程等待变量减少 latch.countDown(); } } } }
运行结果如下:
Thread Thread1 is running. Thread Thread3 is running. Thread Thread2 is running. Thread Thread1 is stop. Thread Thread3 is stop. Thread Thread2 is stop. All works are done.