自定义线程池

  • ThreadPool:线程池主体

    • BlockingQueue<Runnable> taskQueue:任务阻塞队列
    • HashSet<Worker> workers:工作线程集合
    • coreSize:核心线程数
    • timeout + timeUnit:线程空闲超时时间(当前未实现)
  • Worker:工作线程(内部类)

    • 循环执行任务队列中的任务
  • BlockingQueue<T>:自定义阻塞队列

    • 基于ReentrantLockCondition实现生产-消费模型

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(TimeUnit.MILLISECONDS,1000,2,10);
        for (int i = 0; i < 5; i++) {
            int j = i;
            threadPool.execute(()->{
                System.out.println(j);
            });
        }
    }
}
class ThreadPool{
    private BlockingQueue<Runnable> taskQueue;

    private HashSet<Worker> workers = new HashSet();

    private int coreSize;

    private long timeout;

    private TimeUnit timeUnit;

    public void execute(Runnable task){
        synchronized (workers){
            if(workers.size()<coreSize){
                Worker worker = new Worker(task);
                workers.add(worker);
                worker.start();
            }else {
                taskQueue.put(task);
            }
        }
    }



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

    class Worker extends Thread{
        private Runnable task;

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

        @Override
        public void run() {
            while (task!=null || (task=taskQueue.take())!=null){
                try {
                    task.run();
                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    task=null;
                }
            }
            synchronized (workers){
                workers.remove(this);
            }
        }
    }
}

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

    private ReentrantLock lock = new ReentrantLock();

    private Condition consumer = lock.newCondition();

    private Condition product = lock.newCondition();

    private int capacity;

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

    //超时阻塞获取
    public T poll(long timeout, TimeUnit unit){
        lock.lock();
        try {
            long nanos = unit.toNanos(timeout);
            while (queue.isEmpty()){
                try {
                    if(nanos <= 0){
                        return null;
                    }
                    nanos = consumer.awaitNanos(nanos);
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
            }
            T t = queue.removeFirst();
            product.signal();
            return t;
        }finally {
            lock.unlock();
        }
    }

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


    //阻塞添加
    public void put(T element){
        lock.lock();
        try {
        while (queue.size() == capacity){
            try {
                product.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        queue.addLast(element);
        consumer.signal();
        }finally {
            lock.unlock();
        }
    }

    //阻塞大小
    public int size(){
        lock.lock();
        try {
            return queue.size();
        }finally {
            lock.unlock();
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值