和朱晔一起复习Java并发(一):线程池 (3)

我们可以通过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); }

实现这个功能主要依靠两个地方的改进:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zgdxwx.html