zoukankan      html  css  js  c++  java
  • 线程等待——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.
    
  • 相关阅读:
    c++11——列表初始化
    flask学习(十二):for循环遍历
    flask学习(十一):if判断语句
    flask学习(十):模板中访问模型和字典的属性
    flask学习(九):模板渲染和参数传递
    flask学习(八):页面跳转和重定向
    flask学习(七):URL反转
    flask学习(六):URL传参
    flask学习(五):使用配置文件
    flask学习(四):debug模式
  • 原文地址:https://www.cnblogs.com/coshaho/p/5427289.html
Copyright © 2011-2022 走看看