java--自定义线程池(1)

@Slf4j(topic = "w.Test1")
public class Test1 {
    public static void main(String[] args) {
        ThreadPool pool = new ThreadPool(2, 1000, TimeUnit.MICROSECONDS, 10);
        for (int i = 0; i < 5; i++) {
            int j = i;
            pool.execute(() -> log.debug("线程:{}在执行", j));
        }
    }

}

@Slf4j(topic = "w.Test1")
class ThreadPool {
    // 任务队列
    private BlockingQueue<Runnable> taskQueue;
    // 线程集合
    private HashSet<Worker> works = new HashSet<>();
    // 核心线程数
    private int coreSize;
    // 超时时间
    private long timeout;
    // 时间单位
    private TimeUnit timeUnit;

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

    // 执行任务
    public void execute(Runnable task) {
        synchronized (works) {
            if (works.size() < coreSize) {
                Worker worker = new Worker(task);
                // 加入线程池
                log.debug("加入核心线程");
                works.add(worker);
                worker.start();
            } else {
                taskQueue.pull(task);
            }
        }
    }

    class Worker extends Thread {
        private Runnable task;

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

        @Override
        public void run() {
            while (task != null || (task = taskQueue.poll(timeout,timeUnit)) != null) {
                try {
                    task.run();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    task = null;
                }
            }
            synchronized (works) {
                log.debug("移除该线程");
                works.remove(this);
            }
        }
    }

}

// 任务队列
@Slf4j(topic = "w.Test1")
class BlockingQueue<T> {
    private Deque<T> queue = new ArrayDeque<>();
    private ReentrantLock lock = new ReentrantLock();
    // 生产者等待区
    private Condition fullWaitSet = lock.newCondition();
    // 消费者等到区
    private Condition emptyWaitSet = lock.newCondition();
    // 队列上限
    private int capCity;

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

    // 获取永久等待方法
    public T take() {
        lock.lock();
        try {
            while (queue.isEmpty()) {
                try {
                    log.debug("获取方法开始等待");
                    emptyWaitSet.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            T first = queue.removeFirst();
            fullWaitSet.signal();
            return first;
        } finally {
            lock.unlock();
        }
    }

    // 获取带超时等待方法
    public T poll(long timeout, TimeUnit unit) {
        lock.lock();
        try {
            long nanos = unit.toNanos(timeout);
            while (queue.isEmpty()) {
                if (nanos <= 0) {
                    return null;
                }
                try {
                    nanos = emptyWaitSet.awaitNanos(nanos);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            T first = queue.removeFirst();
            fullWaitSet.signal();
            return first;
        } finally {
            lock.unlock();
        }
    }

    // 添加任务方法
    public void pull(T element) {
        lock.lock();
        try {
            while (queue.size() >= capCity) {
                try {
                    log.debug("添加方法开始等待");
                    fullWaitSet.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            queue.addLast(element);
            emptyWaitSet.signal();
        } finally {
            lock.unlock();
        }
    }


}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值