为什么ScheduledExecutorService不会根据需要生成线程?

在我的应用程序中,我使用ScheduledExecutorService,但只生成一个线程来处理计划任务。 这是因为ScheduledExecutorService不会产生线程来处理挂起的任务吗?

这是一个代码片段,它只输出“run()1”而不是预期的“run()1”,然后是“run()2”…“run()10”。

public class App { public static void main(String[] args) { int N = 10; Runnable runner = new Runnable() { public void run() { foo(); } }; for (int i = 0; i < N; i++) { executor.schedule(runner, i, TimeUnit.MILLISECONDS); } } private static void foo() { System.out.println("run() " + (++n)); synchronized (executor) { try { executor.wait(); } catch (InterruptedException ex) { Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex); } } System.out.println("finished()"); } private static Logger logger = Logger.getLogger(App.class.getName()); private static int n = 0; private static ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); } 

只有一个线程,因为您使用Executors.newScheduledThreadPool(1)创建线程池,这意味着线程池只包含1个线程。 如果你想要10个线程,请传递10作为参数。 请注意,此方法返回的ScheduledThreadPoolExecutor文档明确指出线程池具有固定大小。

ScheduledThreadPoolExecutor的javadoc:

虽然这个类inheritance自ThreadPoolExecutor,但是一些inheritance的调优方法对它没用。 特别是,因为它使用corePoolSize线程和无界队列作为固定大小的池,所以对maximumPoolSize的调整没有任何有用的效果。 此外,将corePoolSize设置为零或使用allowCoreThreadTimeOut几乎绝不是一个好主意,因为一旦它们有资格运行,这可能会使池没有线程来处理任务。

换句话说, maximumPoolSize == corePoolSize 。 你将corePoolSize设置为1 ,这样它就会产生。