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

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class DdqThreadPool {
    private static final class DdqThread extends Thread {
        private Runnable runnable;
        private final ReentrantLock reentrantLock = new ReentrantLock();
        private final Condition condition = reentrantLock.newCondition();

        public void setRunnable(Runnable runnable) {
            try {
                reentrantLock.lock();
                this.runnable = runnable;
                condition.signalAll();
            } catch (Exception exception) {
                throw new RuntimeException(exception);
            } finally {
                reentrantLock.unlock();
            }
        }

        @Override
        public void run() {
            while (true) {
                try {
                    reentrantLock.lock();
                    while (runnable == null) condition.await();
                    runnable.run();
                    runnable = null;
                } catch (Exception exception) {
                    throw new RuntimeException(exception);
                } finally {
                    reentrantLock.unlock();
                }
            }

        }
    }

    private List<DdqThread> threads;

    private AtomicInteger threadSize;

    private DdqThreadPool(List<DdqThread> ddqThreads) {
        this.threads = ddqThreads;
        this.threadSize = new AtomicInteger(ddqThreads.size());
    }

    public static DdqThreadPool newDdqThreadPool(int maxThreadSize) {
        if (maxThreadSize < 1) throw new IllegalArgumentException("线程数量必须大于0");
        List<DdqThread> ddqThreads = new LinkedList<>();
        for (int idx = 0; idx < maxThreadSize; idx++) {
            DdqThread ddqThread = new DdqThread();
            ddqThread.start();
            ddqThreads.add(ddqThread);
        }
        return new DdqThreadPool(ddqThreads);
    }

    public void execute(Runnable runnable) {
        if (runnable == null) throw new IllegalArgumentException("runnable不能为null");
        int oldThreadSize1 = threadSize.get();
        if (oldThreadSize1 < 1) return;
        if (!threadSize.compareAndSet(oldThreadSize1, oldThreadSize1 - 1)) return;
        DdqThread idleThread = threads.remove(0);
        idleThread.setRunnable(runnable);
        //以下三段代码可能还存在bug,因为idleThread.setRunnable(runnable)后,由于是异步执行,可能会存在着线程没执行完,但是忙碌线程又被添加回了可用线程集合
        int oldThreadSize2;
        while (!threadSize.compareAndSet((oldThreadSize2 = threadSize.get()), oldThreadSize2 + 1)) ;
        threads.add(idleThread);
    }
}

V2版本请点击此处

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值