多线程处理任务案例(同步锁+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

3、测试结果大致如下:

    多线程处理任务案例(同步锁+StopWatch+CountDownLatch)_第1张图片

4、总结

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

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

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

   
   

你可能感兴趣的:(JAVA基础)