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

11
在我的应用程序中,我使用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);
}

相关:https://dev59.com/yHA75IYBdhLWcg3wVXav - AlikElzin-kilaka
相关链接:http://stackoverflow.com/questions/42495659/how-to-create-a-scheduledexecutorservice-bound-by-only-the-cpu-usage - AlikElzin-kilaka
2个回答

15

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


1
谢谢! 我的问题在于Executors.newScheduledThreadPool()的文档,它明确地没有说明这个特性,而使用的变量名和相同的描述则表明了不同的意思。 - Ivin

6
ScheduledThreadPoolExecutor的javadoc中可以看出:
尽管此类继承自ThreadPoolExecutor,但有一些继承的调整方法对它没有用处。特别地,因为它使用corePoolSize线程和无限队列作为固定大小的池,所以对maximumPoolSize的调整没有任何有用的效果。此外,将corePoolSize设置为零或使用allowCoreThreadTimeOut几乎从来不是一个好主意,因为这可能会使池在任务变得可运行时没有线程来处理它们。
换句话说,maximumPoolSize == corePoolSize。您将corePoolSize设置为1,因此它只会生成一个线程。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接