在我的应用程序中,我使用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);
}
Run Code Online (Sandbox Code Playgroud)
JB *_*zet 10
由于您使用创建线程池Executors.newScheduledThreadPool(1),因此只有一个线程,这意味着线程池仅包含1个线程.如果你想要10个线程,请传递10作为参数.请注意,此方法返回的ScheduledThreadPoolExecutor文档明确指出线程池具有固定大小.
从javadoc ScheduledThreadPoolExecutor:
虽然这个类继承自ThreadPoolExecutor,但是一些继承的调优方法对它没用.特别是,因为它使用corePoolSize线程和无界队列充当固定大小的池,所以对maximumPoolSize的调整没有任何有用的效果.此外,将corePoolSize设置为零或使用allowCoreThreadTimeOut几乎绝不是一个好主意,因为一旦它们有资格运行,这可能会使池没有线程来处理任务.
换句话说,maximumPoolSize == corePoolSize.你设置corePoolSize为1,所以它将产生的全部.