0
点赞
收藏
分享

微信扫一扫

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

是归人不是过客 2024-08-02 阅读 31
import cn.hutool.core.thread.ThreadUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
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<>());
            DdqThread ddqThread = new DdqThread("ddqThread" + idx, idx);
            this.ddqThreads.add(ddqThread);
            ddqThread.start();
        }
    }

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

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

        @Override
        public void run() {
            Queue<Runnable> taskQueue = taskQueues.get(idx);
            Runnable task;
            while (true) {
                if ((task = taskQueue.poll()) == null) continue;
                task.run();
            }
        }
    }

    private int randomIndex() {
        return (int) (Math.random() * taskQueues.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);
    }
    
    public static void main(String[] args) {
        DdqThreadPool ddqThreadPoolV2 = DdqThreadPool.newDdqThreadPool(4);
        for (int i = 0; i < 10; i++) {
            ddqThreadPoolV2.execute(() -> {
                System.out.println(Thread.currentThread().getName());
                ThreadUtil.sleep(1000L);
            });
        }
    }
}

V1版本请点击此处

举报

相关推荐

0 条评论