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