为什么ScheduledExecutorService不会根据需要生成线程? [英] Why doesn't ScheduledExecutorService spawn threads as needed?

查看:140
本文介绍了为什么ScheduledExecutorService不会根据需要生成线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In my application I use ScheduledExecutorService, but only one thread is spawned to handle the scheduled tasks. Is this because ScheduledExecutorService does not spawn threads to handle the pending tasks?

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

Here is a code snippet that will output only "run() 1" instead of the expected "run() 1" followed by "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 的文档,这是该方法返回的内容,明确表示线程池具有固定大小。

There is only one thread because you create the thread pool with Executors.newScheduledThreadPool(1), which means that the thread pool contains only 1 thread. If you want 10 threads, pass 10 as argument. Note that the documentation of ScheduledThreadPoolExecutor, which is what this method returns, explicitly says that the thread pool has a fixed size.

这篇关于为什么ScheduledExecutorService不会根据需要生成线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆