为什么 ExecutorService 不在流中工作?
Why ExecutorService is not working in a stream?
我正在通过流传递一组任务,这是一个简化的演示:
ExecutorService executorService = Executors.newCachedThreadPool((r) -> {
Thread thread = new Thread();
thread.setDaemon(true); // even I removed this, it's still not working;
return thread;
});
IntStream.range(0, TASK_COUNT).forEach(i -> {
executorService.submit(() -> {
out.println(i);
return null;
});
});
所有任务提交后,我尝试等待所有任务完成使用:
executorService.shutdown();
executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
但是输出是none,什么也没有打印出来。
有什么问题吗?任何帮助将不胜感激。
一个奇怪的 find-out 是,当使用默认 DefaultThreadFactory 时,它正在工作。
ExecutorService executorService = Executors.newCachedThreadPool();
F.Y.I 守护线程是我已经检查过的原因。为了调试,我故意设置了它们。
您忘记将 Runnable
传递给 Thread
构造函数:
ExecutorService executorService = Executors.newCachedThreadPool(r -> {
Thread thread = new Thread(r);
^
thread.setDaemon(false);
return thread;
});
我正在通过流传递一组任务,这是一个简化的演示:
ExecutorService executorService = Executors.newCachedThreadPool((r) -> {
Thread thread = new Thread();
thread.setDaemon(true); // even I removed this, it's still not working;
return thread;
});
IntStream.range(0, TASK_COUNT).forEach(i -> {
executorService.submit(() -> {
out.println(i);
return null;
});
});
所有任务提交后,我尝试等待所有任务完成使用:
executorService.shutdown();
executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
但是输出是none,什么也没有打印出来。
有什么问题吗?任何帮助将不胜感激。
一个奇怪的 find-out 是,当使用默认 DefaultThreadFactory 时,它正在工作。
ExecutorService executorService = Executors.newCachedThreadPool();
F.Y.I 守护线程是我已经检查过的原因。为了调试,我故意设置了它们。
您忘记将 Runnable
传递给 Thread
构造函数:
ExecutorService executorService = Executors.newCachedThreadPool(r -> {
Thread thread = new Thread(r);
^
thread.setDaemon(false);
return thread;
});