使用countdownlatch和线程池caCheThreadPool实现任务的分发执行

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u011066470/article/details/86011094

业务逻辑要求:每次调用多个任务,将任务分发给多个子线程,实现并行执行。本代码使用缓存线程池cacheThreadPool初始化多个线程,使用countdownlatch做子线程的计数控制,当子线程执行完,释放执行权,交给主线程,开始下一轮的执行。

话不多说:上代码

public class ExecutorsTest {
private static int count=0;
    //线程数
    /**
     * @param args
     */
    public static void main(String[] args) {
        while (true) {
            if (count == 1) {
                System.out.println("线程名字:"+Thread.currentThread().getName()+" 线程id:"+Thread.currentThread().getId()+"执行结束");
                break;
            }
            //1.获取任务
            List<Integer> taskList = new ArrayList<Integer>();
            for (int k = 0; k < 10; k++) {
                taskList.add(k);
            }
            System.out.println("获取任务结束。。。。。。");
            //线程数
            int num = 5;
            //CountDownLatch是一个同步辅助类也可以使用AtomicInteger替代
            CountDownLatch doneSignal = new CountDownLatch(num);
            ExecutorService pool = Executors.newFixedThreadPool(num);
            for (int i = 0; i < num; i++) {
                //在未来某个时间执行给定的命令
                pool.execute(new WorkerRunnable(doneSignal, i, taskList));
            }
            try {
                System.out.println("开始等待====");
                doneSignal.await();

                System.out.println("开始等待结束====");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //子线程执行完毕,可以开始后续任务处理了
            System.out.println("所有任务执行完毕");
            count++;
            System.out.println("========");

        }

    }

}
package com.test.thread;

import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * Created by liujianfu on 2018/11/14.
 */
public class WorkerRunnable implements  Runnable{
    private final CountDownLatch doneSignal;
    private final int i;
    private static List<Integer> taskList;
    WorkerRunnable(CountDownLatch doneSignal, int i,List<Integer> taskList) {
        this.doneSignal = doneSignal;
        this.i = i;
        this.taskList=taskList;
    }
    public void run() {
        //子线程的任务
        try{
            if(i%2==0){
              //  System.out.println("线程:"+i+"休眠。。。。。");
                System.out.println("线程名字:"+Thread.currentThread().getName()+" 线程id:"+Thread.currentThread().getId()+"休眠:");
                Thread.sleep(5000);
            }
            doWork(i);
        }catch (Exception e) {
            e.printStackTrace();
        }
        //任务执行完毕递减锁存器的计数
        doneSignal.countDown();
        System.out.println("线程名字:"+Thread.currentThread().getName()+" 线程id:"+Thread.currentThread().getId()+"count--");
    }

    void doWork(int i) {
        int totalSize = taskList.size();
        int ts = 5;
        if (ts > totalSize) {
            ts = totalSize;
        }
        int m = totalSize / ts;

        int startIndex = i * m;
        int endIndex = (i + 1) * m;
        if (i == ts - 1) {
            endIndex = totalSize;
        }
        List<Integer> tempIds = taskList.subList(startIndex, endIndex);
        for(int k=0;k<tempIds.size();k++){
            System.out.println("线程名字:"+Thread.currentThread().getName()+" 线程id:"+Thread.currentThread().getId()+"消费任务:"+tempIds.get(k));
        }
        System.out.println("======================线程名字:"+Thread.currentThread().getName()+" 线程id:"+Thread.currentThread().getId()+"本线程消费结束=================");
    }

}

执行结果:


获取任务结束。。。。。。
开始等待====
线程名字:pool-1-thread-5 线程id:15休眠:
线程名字:pool-1-thread-3 线程id:13休眠:
线程名字:pool-1-thread-1 线程id:11休眠:
线程名字:pool-1-thread-4 线程id:14消费任务:6
线程名字:pool-1-thread-4 线程id:14消费任务:7
======================线程名字:pool-1-thread-4 线程id:14本线程消费结束=================
线程名字:pool-1-thread-4 线程id:14count--
线程名字:pool-1-thread-2 线程id:12消费任务:2
线程名字:pool-1-thread-2 线程id:12消费任务:3
======================线程名字:pool-1-thread-2 线程id:12本线程消费结束=================
线程名字:pool-1-thread-2 线程id:12count--
线程名字:pool-1-thread-3 线程id:13消费任务:4
线程名字:pool-1-thread-3 线程id:13消费任务:5
======================线程名字:pool-1-thread-3 线程id:13本线程消费结束=================
线程名字:pool-1-thread-3 线程id:13count--
线程名字:pool-1-thread-5 线程id:15消费任务:8
线程名字:pool-1-thread-5 线程id:15消费任务:9
======================线程名字:pool-1-thread-5 线程id:15本线程消费结束=================
线程名字:pool-1-thread-5 线程id:15count--
线程名字:pool-1-thread-1 线程id:11消费任务:0
线程名字:pool-1-thread-1 线程id:11消费任务:1
======================线程名字:pool-1-thread-1 线程id:11本线程消费结束=================
线程名字:pool-1-thread-1 线程id:11count--
开始等待结束====
所有任务执行完毕
========
线程名字:main 线程id:1执行结束
都看到这里了,就顺手点击左上角的【关注】按钮,点击右上角的小手,给个评论,关注一下,再走呗!☺

猜你喜欢

转载自blog.csdn.net/u011066470/article/details/86011094