多线程处理任务案例(同步锁+StopWatch+CountDownLatch)

今天抽空写了一个通过spring线程池来实现多线程处理任务的性能问题。这个代码相对简单,文字描述相对较少。大家有疑问可以回复。

1、任务线程代码

package com.yufeicms.test;

import java.util.concurrent.CountDownLatch;

public class MyThread implements  Runnable{

    private  int  currentIndex;//当前待处理的任务下标

    private  int  maxIndex;//最大小标

    private int[] idArr;//任务数据ID

    private Object  obj = new Object();//做同步锁

    private CountDownLatch countDownLatch;//监听所有线程任务执行完毕

    public MyThread(int[] idArr, CountDownLatch countDownLatch){
        this.maxIndex = idArr.length-1;
        this.idArr = idArr;
        this.countDownLatch = countDownLatch;
    }
    @Override
    public void run() {
         while (true){
             if(currentIndex > maxIndex){
                 break;
             }
             int  id;
             synchronized (obj){
                 if(++currentIndex > maxIndex){
                     break;
                 }
             }
             id = idArr[currentIndex];
             handle(id);
         }
        countDownLatch.countDown();
    }

    private  void  handle(int id){
        System.out.println("开始处理"+Thread.currentThread().getName()+"文章ID:"+id);
        try{
            Thread.sleep(1000);//模拟处理任务
        }catch (Exception e){
            e.printStackTrace();
        }
        System.out.println("结束处理"+Thread.currentThread().getName()+"文章ID:"+id);
    }
}

2、测试类代码

package com.yufeicms.test;

import org.apache.commons.lang3.time.StopWatch;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Test {
    public static void main(String[] args) throws InterruptedException {
        int nThreads = 10;
        ExecutorService pool = Executors.newFixedThreadPool(nThreads);
        CountDownLatch countDownLatch = new CountDownLatch(nThreads);
        StopWatch stopWatch = new StopWatch();
        int[]  idArr = new int[100];
        for(int i =0 ; i< 100; i++){
            idArr[i]=i+10000;
        }
        stopWatch.start();
        MyThread myThread = new MyThread(idArr,countDownLatch);
        for(int i=0;i<nThreads;i++){
            pool.execute(new Thread(myThread));
        }
        countDownLatch.await();
        stopWatch.stop();
        System.out.println("执行完所有任务所需时间:"+stopWatch.getTime()/1000+"秒");
        pool.shutdown();
    }
}

3、测试结果大致如下:

    

4、总结

1、由于任务并未做具体事情,通过Thread.sleep()方法,所以cpu资源是让出来了的。所以线程数*耗时=任务数;

2、代码中使用stopwatch用来计时;

3、代码中使用CountDownLatch来保证时间的准确性。

  
  
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值