手写线程池

@Slf4j(topic = "c.TestPool")
public class Singleton {
    public static void main(String[] args) {
        ThreadPool threadPool = new ThreadPool(2,
                1000, TimeUnit.MILLISECONDS, 1, (queue, task)->{
            // 1) 放到任务队列(满的话主线程死等)
             queue.put(task);
            // 2) 放到任务队列(满的话主线程超时等待)
            // queue.putWithTimeOut(task, 1500, TimeUnit.MILLISECONDS);
            // 3) 调用者放弃任务执行
            // log.debug("放弃{}", task);
            // 4) 调用者抛出异常
            // throw new RuntimeException("任务执行失败 " + task);
            // 5) 调用者自己执行任务
            // task.run();
        });
        for (int i = 0; i < 5; i++) {
            int j = i;
            threadPool.execute(() -> {
                // task
                log.debug("{}",j);
            });
        }
    }
}

// 任务队列满时的拒绝策略
@FunctionalInterface
interface RejectPolicy<T> {
    void reject(BlockingQueue<T> queue, T task);
}

// 线程池
@Slf4j(topic = "c.ThreadPool")
class ThreadPool {
    // 任务队列
    private BlockingQueue<Runnable> taskQueue;
    // 线程集合
    private HashSet<Worker> threads = new HashSet<>();
    // 线程数上限
    private int coreSize;
    // 获取任务时的超时时间
    private long timeout;
    private TimeUnit timeUnit;
    private RejectPolicy<Runnable> rejectPolicy;

    public ThreadPool(int coreSize, long timeout, TimeUnit timeUnit, int queueCapcity, RejectPolicy<Runnable> rejectPolicy) {
        this.coreSize = coreSize;
        this.timeout = timeout;
        this.timeUnit = timeUnit;
        this.taskQueue = new BlockingQueue<>(queueCapcity);
        this.rejectPolicy = rejectPolicy;
    }

    class Worker extends Thread{
        private Runnable task;
        public Worker(Runnable task) {
            super(task,String.format("线程%s",threads.size() + 1));
            this.task = task;
        }
        @Override
        public void run() {
            // 执行完task后,并不立即结束,看还有没有下一个task
            while(task != null || (task = taskQueue.get()) != null) {
                try {
                    task.run();
                    log.debug("线程:{}将任务:{}执行完毕",this.getName(),Integer.toHexString(task.hashCode()));
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    task = null;
                }
            }
            synchronized (threads) {
                log.debug("移除线程:{}",this.getName());
                threads.remove(this);
            }
        }
    }

    // 执行任务
    public void execute(Runnable task) {
        synchronized (threads) {
            if(threads.size() < coreSize) {
                Worker worker = new Worker(task);
                threads.add(worker);
                log.debug("新增线程:{},任务:{}",worker.getName(),Integer.toHexString(task.hashCode()));
                worker.start();
            } else {
                // 活跃线程数(正在执行任务的 + 等待新任务的)等于容量
                taskQueue.tryPut(rejectPolicy, task);
            }
        }
    }
}

// 任务队列
@Slf4j(topic = "c.BlockingQueue")
class BlockingQueue<T> {
    // 任务队列
    private Deque<T> queue = new ArrayDeque<>();
    // 锁
    private ReentrantLock lock = new ReentrantLock();
    // (等待任务队列空位)
    private Condition taskPuttersWaitSet = lock.newCondition();
    // (线程池中的线程等待任务)
    private Condition taskGettersWaitSet = lock.newCondition();
    // 队列容量
    private int taskQueueCapacity;

    public BlockingQueue(int taskQueueCapacity) {
        this.taskQueueCapacity = taskQueueCapacity;
    }

    // 获取任务
    public T getWithTimeOut(long timeout, TimeUnit unit) {
        lock.lock();
        try {
            long nanos = unit.toNanos(timeout);
            while (queue.isEmpty()) {
                try {
                    if (nanos <= 0) {
                        return null;
                    }
                    nanos = taskGettersWaitSet.awaitNanos(nanos);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            T t = queue.removeFirst();
            taskPuttersWaitSet.signal();
            return t;
        } finally {
            lock.unlock();
        }
    }
    public T get() {
        lock.lock();
        try {
            while (queue.isEmpty()) {
                try {
                    log.debug("线程:{}等待新任务",Thread.currentThread().getName());
                    taskGettersWaitSet.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            T t = queue.removeFirst();
            log.debug("线程:{}拿到新任务:{}",Thread.currentThread().getName(),Integer.toHexString(t.hashCode()));
            taskPuttersWaitSet.signal();
            return t;
        } finally {
            lock.unlock();
        }
    }

    // 添加任务
    public void put(T task) {
        lock.lock();
        try {
            while (queue.size() == taskQueueCapacity) {
                try {
                    log.debug("任务:{}等待任务队列空位",Integer.toHexString(task.hashCode()));
                    taskPuttersWaitSet.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            queue.addLast(task);
            log.debug("任务:{}已放入任务队列",Integer.toHexString(task.hashCode()));
            taskGettersWaitSet.signal();
        } finally {
            lock.unlock();
        }
    }
    public boolean putWithTimeOut(T task, long timeout, TimeUnit unit) {
        lock.lock();
        try {
            long nanos = unit.toNanos(timeout);
            while (queue.size() == taskQueueCapacity) {
                try {
                    if(nanos <= 0) {
                        return false;
                    }
                    nanos = taskPuttersWaitSet.awaitNanos(nanos); // 返回剩余等待时间
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            queue.addLast(task);
            taskGettersWaitSet.signal();
            return true;
        } finally {
            lock.unlock();
        }
    }

    public void tryPut(RejectPolicy<T> rejectPolicy, T task) {
        lock.lock();
        try {
            if(queue.size() == taskQueueCapacity) {
                rejectPolicy.reject(this, task);
            } else {
                queue.addLast(task);
                log.debug("任务:{}已放入任务队列",Integer.toHexString(task.hashCode()));
                taskGettersWaitSet.signal();
            }
        } finally {
            lock.unlock();
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值