让ThreadPoolExecutor的workQueue占满时自动阻塞submit()方法

public class BlockingSubmitExecutor {

    private ExecutorService executor =
            new ThreadPoolExecutor(2, 2 * 2, 1, TimeUnit.MINUTES, new OfferBlockingQueue<>(10),
                    new ThreadFactoryBuilder().setNameFormat("push-scheduler-%d").build(),
                    new ThreadPoolExecutor.AbortPolicy());

    private static final class OfferBlockingQueue<E> extends LinkedBlockingQueue<E> {

        public OfferBlockingQueue(int capacity) {
            super(capacity);
        }

        @Override
        public boolean offer(@NotNull E e) {
            try {
                // ThreadPoolExecutor 底层workQueue调用的offer来入队.offer不会block,这里改成put,当队列满时可阻塞住submit
                put(e);
                return true;
            } catch (InterruptedException ex) {
                Thread.currentThread().interrupt();
                return false;
            }
        }

    }

    @Test
    public void test() {
        for (int i = 0; i < 10; i++) {
            int finalI = i;
            executor.submit(() -> {
                System.out.println("Thread start:" + finalI);
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("Thread finish:" + finalI);
            });
        }

        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

参考:
https://www.codelast.com/原创-让threadpoolexecutor的workqueue占满时自动阻塞submit方法/

原文地址:https://www.cnblogs.com/acbingo/p/11907062.html