Java 8 为什么ExecutorService不在流中工作?

Java 8 为什么ExecutorService不在流中工作?,java-8,executorservice,Java 8,Executorservice,我正在通过流传递一组任务,下面是一个简化的演示: ExecutorService executorService = Executors.newCachedThreadPool((r) -> { Thread thread = new Thread(); thread.setDaemon(true); // even I removed this, it's still not working; 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);
但是输出是无的,没有打印出来

出什么事了?任何帮助都将不胜感激

一个奇怪的发现是,当使用默认的DefaultThreadFactory时,它工作正常

ExecutorService executorService = Executors.newCachedThreadPool();

F.Y.I守护进程线程是我已经检查过的原因。为了调试,我特意设置了它们

您忘记将
Runnable
传递给
线程
构造函数:

ExecutorService executorService = Executors.newCachedThreadPool(r -> {
    Thread thread = new Thread(r);
                               ^
    thread.setDaemon(false);
    return thread;
});

顺便说一句,做同样事情的简单方法是
IntStream.range(0,TASK\u COUNT).parallel().forEach(System.out::println)这将使用您不需要管理的后台守护进程线程池,在您机器上的所有处理器之间分配工作。@PeterLawrey,谢谢提醒。我知道这个方法。但是后台线程池并没有像我所希望的那样创建守护进程线程。此外,在java-8中传递一个简单的线程工厂现在更容易了。谢谢你的回复。