java简单实现一个阻塞式线程池

public class BlockedThreadPoolExecutor extends ThreadPoolExecutor {

    private final Semaphore semaphore;

    public BlockedThreadPoolExecutor(int poolSize) {
        super(0, Integer.MAX_VALUE,
                60L, TimeUnit.SECONDS,
                new SynchronousQueue<>());
        semaphore = new Semaphore(poolSize);
    }
    
    @Override
    public void execute(Runnable command) {
        try {
            semaphore.acquire();
            super.execute(command);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void afterExecute(Runnable r, Throwable t) {
        super.afterExecute(r, t);
        semaphore.release();
    }
}

 

posted on 2020-11-03 14:13  SunEn  阅读(244)  评论(0编辑  收藏  举报

导航