package com.zzsn.job;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 阻塞线程池
 * 线程池的线程数到达最大线程数阻塞等待
 * 可用于多线程获取MQ消息任务
 * 因为会阻塞，就不用考虑拒绝策略这一块的重写
 */
public class BlockThreadPoolExecute extends ThreadPoolExecutor {
    private ReentrantLock lock = new ReentrantLock();
    private Condition condition = this.lock.newCondition();
 
    public BlockThreadPoolExecute(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
    }
 
    @Override
    public void execute(Runnable command) {
        //进行同步锁定
        this.lock.lock();
        super.execute(command);
        try {
            //如果线程池的数量已经达到最大线程池的数量,则进行挂起操作
            if (getPoolSize() == getMaximumPoolSize()) {
                this.condition.await();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            this.lock.unlock();
        }
    }
    @Override
    protected void afterExecute(Runnable r, Throwable t) {
        try{
            lock.lock();
            this.condition.signal();
        }finally {
            this.lock.unlock();
        }
 
 
    }
}