java - executor.invokeAll() 未完成执行

标签 java multithreading java-8 java-stream executorservice

所以我正在尝试在“玩具语言”上实现某种 fork 。这就像实现我自己的编译器。因此,当用户进行 fork 时,我的程序应该启动/模拟一些线程。 在我的代码中,我准备了可调用对象,然后开始执行可调用对象,但是当我使用 invokeAll 时,我的程序不会终止,它只是不执行任何操作。

我通过调试运行了代码,当我调用 invokeAll() 时,它只是停止调试,但它不会终止或抛出错误或任何东西(我在 try-catch 中调用了)。我也尝试过使用固定线程池。它没有做任何事情

一些代码:

// preparing the callables
java.util.List<Callable<MyClass>> callList = prgll.stream()
        .map(p -> (Callable<MyClass>) () -> {
    return p.oneStep(); //a method from my class
}).collect(Collectors.toList());

//start the execution of the callables
//it should return the list of new created threads
ExecutorService executor = Executors.newSingleThreadExecutor();
java.util.List<MyClass> fff;
try {
    fff = executor.invokeAll(callList).stream() // here my program gets blocked but not all the time, only when I call use myFork class
    .map(future-> {
        try {
            return future.get();
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("Error in onestepforall" + e.getMessage());
        }
    }).filter(p->p != null).collect(Collectors.toList());

} catch (InterruptedException e) {
    e.printStackTrace();
    throw new CustomException("Error while trying executor" +e.getMessage());
}

我可以调试它以更深入地了解我的代码,以准确了解 invokeAll 保持待机状态的原因吗?

我还尝试从新的 SingleThread 更改为固定池,但它仍然没有执行任何操作。

最佳答案

invokeAll() 是一种阻塞方法,即它会等待所有 future 完成。

.map 通过执行器的 submit() 可调用列表,而不是如果您想要异步任务提交。

如果您的问题是为什么任务没有完成,那么您不想调试提交给执行器的线程,而是调试生成的线程,因为任务是在单独的线程上执行的。您可以简单地使用附加的调试器挂起整个 JVM,然后查看各个线程,而不是使用断点。

关于java - executor.invokeAll() 未完成执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34467551/

相关文章:

Java BufferedWriter 创建空字符

java - 将 Comparable 的实例传递给需要 Comparator 的方法

Java 8 List<T> 到 Map<K, V>

java - 如何对包含整数的字符串列表进行排序

java - Android数据库最佳实践

java - Jackson - 获取数组内的条目

java - 为什么有这么多 TIMED_WAITING 线程?

java - 线程中的异常 "main"java.lang.StringIndexOutOfBoundsException : String index out of range:

java - 从本地机器上的多个线程通过 RMI 调用线程安全方法是否安全?

java - 当从匿名内部类或 lambda 访问时,为什么数组的值被视为 Final 或 "effectively final"?