ledThreadPoolExecutor和corePoolSi

ledThreadPoolExecutor和corePoolSi

本文介绍了ScheduledThreadPoolExecutor和corePoolSize 0?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想有一个 ScheduledThreadPoolExecutor ,它还会停止最后一个线程,如果没有工作要做,并创建(并保持线程活着一段时间)if有新的任务。

I'd like to have a ScheduledThreadPoolExecutor which also stops the last thread if there is no work to do, and creates (and keeps threads alive for some time) if there are new tasks. But once there is no more work to do, it should again discard all threads.

我天真地创建为新的ScheduledThreadPoolExecutor(0),因此,不会创建任何线程,也不会执行任何计划的任务。

I naivly created it as new ScheduledThreadPoolExecutor(0) but as a consequence, no thread is ever created, nor any scheduled task is ever executed.

任何人都可以告诉我,如果我能实现我的目标,在 ScheduledThreadpoolExecutor

Can anybody tell me if I can achieve my goal without writing my own wrapper around the ScheduledThreadpoolExecutor?

提前感谢!

推荐答案

实际上你可以这样做,但它的非显而易见的:

Actually you can do it, but its non-obvious:



  • 在构造函数中将核心线程设置为所需的最大线程数

  • 设置执行器的keepAliveTime

  • 并且最后允许核心线程超时

  • Create a new ScheduledThreadPoolExecutor
  • In the constructor set the core threads to the maximum number of threads you want
  • set the keepAliveTime of the executor
  • and at last, allow the core threads to timeout

m_Executor = new ScheduledThreadPoolExecutor ( 16,null );
m_Executor.setKeepAliveTime ( 5, TimeUnit.SECONDS );
m_Executor.allowCoreThreadTimeOut ( true );

这仅适用于Java 6,但

This works only with Java 6 though

这篇关于ScheduledThreadPoolExecutor和corePoolSize 0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 17:08