自定义一个简易的java线程池

class ThreadPool {
    //任务队列
    private BlockQueue<Runnable> taskQueue;
    
    //线程数量,用来指定线程集合的最大个数
    private int coreSize;

    // 线程集合
    private List<Worker> workers = new Vector<>();

    //线程等待时间
    private long takeTime;

    //线程等待时间单位
    private TimeUnit takeTimeUnit;

    public ThreadPool (int coreSize, int taskQueueCapacity,long takeTime, TimeUnit takeTimeUnit) {
        this.taskQueue = new BlockQueue<>(taskQueueCapacity);
        this.coreSize = coreSize;
        this.takeTime = takeTime;
        this.takeTimeUnit = takeTimeUnit;

    }

    /**
     * 任务执行方法
     * @param task
     */
    public void execute(Runnable task) {
        synchronized (workers) {
            //如果线程集合中的线程数量小于指定线程数量就新建线程,并添加到线程集合中
            //否则就将任务尝试添加到任务队列中去.如果任务队列已经满了,哪个指定处理策略
            if (workers.size() < coreSize) {
                Worker worker = new Worker(task);
                workers.add(worker);
                worker.start();
            } else {
                taskQueue.tryPut(task, (blockQueue, t) -> {
                    task.run();
                });

            }
        }


    }

    class Worker extends Thread {

        Runnable task;

        public Worker(Runnable task) {
            this.task = task;
        }
        @Override
        public void run() {
            //一个任务执行完之后就会尝试从任务队列里去任务
            while (task != null || (task = taskQueue.take(takeTime, takeTimeUnit)) != null) {
                try {
                    //Thread.sleep(1000);
                    task.run();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    task = null;
                }

            }
            synchronized (workers) {
                workers.remove(this);
            }

        }
    }
}



class BlockQueue<T> {

    private Deque<T> queue = new ArrayDeque<T>();

    private ReentrantLock lock = new ReentrantLock();

    //当任务队列已经满了的条件
    private Condition fullWaitSet = lock.newCondition();

    //当任务队列为空的条件
    private Condition emptyWaitSet = lock.newCondition();

    //任务队列的容量
    private int capacity;

    public BlockQueue(int capacity) {
        this.capacity = capacity;
    }

    public T take() {
        lock.lock();
        try {
            while (queue.isEmpty()) {
                try {
                    emptyWaitSet.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            fullWaitSet.signal();
            return queue.removeFirst();
        } finally {
            lock.unlock();
        }
    }

    public T take(long time, TimeUnit timeUnit) {
        long nanos = timeUnit.toNanos(time);
        lock.lock();
        try {
            while (queue.isEmpty()) {
                try {
                    if (nanos <= 0) {
                        return null;
                    }
                    nanos = emptyWaitSet.awaitNanos(nanos);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            fullWaitSet.signal();
            return queue.removeFirst();
        } finally {
            lock.unlock();
        }
    }

    public void tryPut(T t, BiConsumer<BlockQueue<T>, T> consumer) {
        lock.lock();
        try {
            if (queue.size() < capacity) {
                queue.addLast(t);
                emptyWaitSet.signal();
            } else {
                consumer.accept(this, t);
            }
        } finally {
            lock.unlock();
        }
    }

    public void put(T t) {
        System.out.println(queue.size());
        lock.lock();
        try {
            while (queue.size() == capacity) {
                try {
                    fullWaitSet.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            queue.addLast(t);
        } finally {
            lock.unlock();
        }
    }


}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值