我们可以通过Hack的方式来实现:
@Test public void test2() throws InterruptedException { AtomicInteger atomicInteger = new AtomicInteger(); BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>(10) { @Override public boolean offer(Runnable e) { return false; } }; ThreadPoolExecutor threadPool = new ThreadPoolExecutor( 2, 5, 5, TimeUnit.SECONDS, queue, new ThreadFactoryImpl("elastic-pool"), (r, executor) -> { try { executor.getQueue().put(r); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }); threadPool.allowCoreThreadTimeOut(true); printStats(threadPool); submitTasks(atomicInteger,threadPool); threadPool.shutdown(); threadPool.awaitTermination(1, TimeUnit.HOURS); }实现这个功能主要依靠两个地方的改进: