java手写简易版自定义线程池 V2

java 复制代码
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;

public class DdqThreadPool {
    private final List<Queue<Runnable>> taskQueues;
    private final List<DdqThread> ddqThreads;

    private DdqThreadPool(int maxThreadSize) {
        this.taskQueues = new ArrayList<>(maxThreadSize);
        this.ddqThreads = new ArrayList<>(maxThreadSize);
        for (int idx = 0; idx < maxThreadSize; idx++) {
            this.taskQueues.add(new LinkedBlockingQueue<>());
            this.ddqThreads.add(new DdqThread("ddqThread" + idx, idx));
        }
        this.ddqThreads.forEach(DdqThread::start);
    }

    private final class DdqThread extends Thread {
        private final int idx;

        private DdqThread(String name, int idx) {
            super(name);
            this.idx = idx;
        }

        private void doRun() {
            Queue<Runnable> taskQueue = taskQueues.get(idx);
            Runnable task;
            while (true) {
                try {
                    if ((task = taskQueue.poll()) != null) task.run();
                } catch (Exception exception) {
                    exception.printStackTrace();
                }
            }
        }

        @Override
        public void run() {
            doRun();
        }
    }

    private int randomIndex() {
        return (int) (Math.random() * taskQueues.size());
    }

    public int poolSize() {
        return ddqThreads.size();
    }

    public void execute(Runnable task) {
        if (task == null) throw new IllegalArgumentException("runnable不能为null");
        taskQueues.get(randomIndex()).offer(task);
    }

    public static DdqThreadPool newDdqThreadPool(int maxThreadSize) {
        if (maxThreadSize < 1) throw new IllegalArgumentException("线程数量必须大于0");
        return new DdqThreadPool(maxThreadSize);
    }

    private static void test1() throws Exception {
        DdqThreadPool ddqThreadPool = DdqThreadPool.newDdqThreadPool(5);
        CountDownLatch countDownLatch = new CountDownLatch(1000);
        long start = System.currentTimeMillis();
        for (int i = 0; i < 1000; i++) {
            ddqThreadPool.execute(countDownLatch::countDown);
        }
        countDownLatch.await();
        long end = System.currentTimeMillis();
        System.out.println("ddqThreadPool:" + (end - start));
    }

    private static void test2() throws Exception {
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        CountDownLatch countDownLatch = new CountDownLatch(1000);
        long start = System.currentTimeMillis();
        for (int i = 0; i < 1000; i++) {
            executorService.execute(countDownLatch::countDown);
        }
        countDownLatch.await();
        long end = System.currentTimeMillis();
        System.out.println("executorService:" + (end - start));
    }

    private static void test3() throws Exception {
        CountDownLatch countDownLatch = new CountDownLatch(1000);
        long start = System.currentTimeMillis();
        for (int i = 0; i < 1000; i++) {
            new Thread(countDownLatch::countDown).start();
        }
        countDownLatch.await();
        long end = System.currentTimeMillis();
        System.out.println("普通thread:" + (end - start));
    }

    private static void sleep(long timeout) {
        try {
            Thread.sleep(timeout);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) throws Exception {
        //自定义的线程池进行测试 cost 8ms
        test1();
        sleep(3000L);
        //java juc自带的线程池进行测试 cost 79ms
        test2();
        sleep(3000L);
        //最原始的线程池进行测试 cost 543ms
        test3();
    }
}

V1版本请点击此处

相关推荐
java1234_小锋1 分钟前
MyBatis如何处理延迟加载?
java·开发语言
菠萝咕噜肉i2 分钟前
MyBatis是什么?为什么有全自动ORM框架还是MyBatis比较受欢迎?
java·mybatis·框架·半自动
林的快手17 分钟前
209.长度最小的子数组
java·数据结构·数据库·python·算法·leetcode
FeboReigns19 分钟前
C++简明教程(10)(初识类)
c语言·开发语言·c++
学前端的小朱20 分钟前
处理字体图标、js、html及其他资源
开发语言·javascript·webpack·html·打包工具
向阳12181 小时前
mybatis 缓存
java·缓存·mybatis
上等猿1 小时前
函数式编程&Lambda表达式
java
摇光931 小时前
js高阶-async与事件循环
开发语言·javascript·事件循环·宏任务·微任务
沐泽Mu1 小时前
嵌入式学习-QT-Day09
开发语言·qt·学习
蓝染-惣右介1 小时前
【23种设计模式·全精解析 | 行为型模式篇】11种行为型模式的结构概述、案例实现、优缺点、扩展对比、使用场景、源码解析
java·设计模式