手写ThreadPool

1.实现阻塞队列
2.实现拒绝策略
3.实现线程池的execute

package com.melioudas.pool;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashSet;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

//线程池的实现
public class TestPool {

    public static void main(String[] args) {
        ThreadPool threadPool = new ThreadPool(1, 1000l, TimeUnit.MILLISECONDS, 3, (blockingQueue, task) -> {
//            blockingQueue.put(task);
            // 1) 傻等着 queue.put(task);//
            // 2) 带超时等待 queue.offer(task, 1500, TimeUnit.MILLISECONDS);
            // 3) 让调用者放弃任务执行 log.debug("放弃{}", task);什么也不写就放弃了
            // 4) 让调用者抛出异常   throw new RuntimeException("任务执行失败 " + task);//
            // 5) 让调用者自己执行任务
//            Runnable task1 = (Runnable)task;
//            task1.run();
           ;
        });
        for (int i = 0; i < 6; i++) {
            int j = i;
            threadPool.execute(() -> {
                try {
                    Thread.sleep(999l);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(j);
            });
        }
    }
}

//拒绝策略
@FunctionalInterface
interface RejectPolicy<T> {
    void reject(BlockingQueue queue, T task);
}

class ThreadPool {
    //1.任务队列
    private BlockingQueue taskQueue;
    //2.线程集合
    private HashSet<Worker> workers = new HashSet<Worker>();
    //3.核心线程数
    private int coreSize;
    //4.获取任务的超时时间
    private long timeout;
    private TimeUnit unit;

    //5.拒绝策略
    private RejectPolicy<Runnable> rejectPolicy;

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

    public void execute(Runnable task) {
        //锁一下workers保证wokers的线程安全
        synchronized (workers) {
            //1.如果任务数没超过coreSize 直接执行
            if (coreSize > workers.size()) {
                Worker worker = new Worker(task);
                System.out.println(Thread.currentThread() + "新增worker对象。。。" + worker);
                workers.add(worker);
                worker.start();
            } else {
                //2.如果任务数超过coreSize 要进入阻塞队列
//                System.out.println(Thread.currentThread() + "放进阻塞队列。。" + task);
//                taskQueue.put(task);
                //使用拒绝策略
                taskQueue.tryPut(rejectPolicy, task);
            }
        }
    }

    class Worker extends Thread {
        private Runnable task;

        public Worker(Runnable task) {
            this.task = task;
        }

        @Override
        public void run() {
            //执行任务
            //1.当任务不为null直接执行
            //2.当任务执行完后如果任务队列中还有任务,则执行队列中的任务

//            while (task != null || (task = (Runnable) taskQueue.take()) != null) {
            while (task != null || (task = (Runnable) taskQueue.poll(1000l, TimeUnit.MILLISECONDS)) != null) {
                try {
                    task.run();
                } finally {
                    task = null;
                }
            }
            synchronized (workers) {
                workers.remove(this);
            }
        }
    }


}

//阻塞队列的实现
class BlockingQueue<T> {
    //1.队列
    Deque<T> queue = new ArrayDeque<>();
    //2.容量
    private int capcity;
    //3.锁   进出队列要保证线程安全
    ReentrantLock lock = new ReentrantLock();
    //4.进入队列的条件锁  生产者条件
    private Condition fullWaitSet = lock.newCondition();
    //5.出队列条件锁  消费者条件
    private Condition emptyWaitSet = lock.newCondition();

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

    //阻塞获取
    public T take() {
        lock.lock();
        try {
            while (queue.isEmpty()) {
                try {
                    emptyWaitSet.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            T t = queue.removeFirst();
            fullWaitSet.signal();
            return t;
        } finally {
            lock.unlock();
        }

    }

    //超时获取
    public T poll(Long timeout, TimeUnit unit) {
        lock.lock();
        try {
            long nanos = unit.toNanos(timeout);
            while (queue.isEmpty()) {
                try {
                    //超时时 直接返回null
                    if (nanos <= 0) {
                        return null;
                    }
                    //awaitNanos 等待纳秒,当打断后返回剩余的纳秒值
                    nanos = emptyWaitSet.awaitNanos(nanos);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            T t = queue.removeFirst();
            fullWaitSet.signal();
            return t;
        } finally {
            lock.unlock();
        }

    }


    //阻塞添加
    public void put(T element) {
        lock.lock();
        try {
            while (queue.size() == capcity) {
                try {
                    System.out.println("傻等着。。。");
                    fullWaitSet.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            queue.addLast(element);
            emptyWaitSet.signal();
        } finally {
            lock.unlock();
        }

    }

    //超时添加
    public boolean offer(T task, long timeout, TimeUnit unit) {
        lock.unlock();
        try {
            long nanos = unit.toNanos(timeout);
            while (queue.size() == capcity) {
                if (nanos <= 0) return false;
                try {
                    nanos = fullWaitSet.awaitNanos(nanos);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            queue.addLast(task);
            emptyWaitSet.signal();
            return true;
        } finally {
            lock.unlock();
        }
    }

    //获得队列大小
    public int size() {
        try {
            lock.lock();
            return queue.size();
        } finally {
            lock.unlock();
        }
    }

    public void tryPut(RejectPolicy<T> rejectPolicy, T task) {
        lock.lock();
        try {
            if (capcity == queue.size()) {
                System.out.println("拒绝了");
                rejectPolicy.reject(this, task);
            } else {
                queue.addLast(task);
                emptyWaitSet.signal();
            }
        } finally {
            lock.unlock();
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值