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版本请点击此处

相关推荐
future141233 分钟前
C#每日学习日记
java·学习·c#
coding随想37 分钟前
JavaScript中的BOM:Window对象全解析
开发语言·javascript·ecmascript
一个混子程序员39 分钟前
SpringBoot自定义Schedule注解
java
心之语歌43 分钟前
Java高效压缩技巧:ZipOutputStream详解
java·后端
booooooty1 小时前
基于Spring AI Alibaba的多智能体RAG应用
java·人工智能·spring·多智能体·rag·spring ai·ai alibaba
猴哥源码1 小时前
基于Java+SpringBoot的健身房管理系统
java·spring boot
极光雨雨1 小时前
Spring Bean 控制销毁顺序的方法总结
java·spring
猴哥源码1 小时前
基于Java+SpringBoot的三国之家网站
java·spring boot
念九_ysl1 小时前
Java 使用 OpenHTMLToPDF + Batik 将含 SVG 遮罩的 HTML 转为 PDF 的完整实践
java·开发语言·pdf
yaoxin5211231 小时前
124. Java 泛型 - 有界类型参数
java·开发语言