Java 多线程执行器InvokeAll问题

Java Multi-Thread Executor InvokeAll Problems

我遇到问题的代码是:

Executor executor = (Executor) callList;

    List<ProgState> newProgList = executor.invokeAll(callList).stream()
            .map(future -> {try {return future.get();} catch(Exception e){e.printStackTrace();}})
            .filter(p -> p!=null).collect(Collectors.toList());

The method invokeAll(List>) is undefined for the type Executor

有人告诉我应该使用像代码片段中那样的执行程序。

可调用对象在以下代码中定义:

List<Callable<ProgState>> callList = (List<Callable<ProgState>>) lst.stream()
            .map(p -> ((Callable<ProgState>)(() -> {return p.oneStep();})))
            .collect(Collectors.toList());

老师代码如下:

//prepare the list of callables

 List<Callable<PrgState>> callList = prgList.stream().map(p -> (() -> {return p.oneStep();})).collect(Collectors.toList());

//start the execution of the callables
//it returns the list of new created threads

List<PrgState> newPrgList = executor.invokeAll(callList).stream()
.map(future -> { try {
 return future.get();
 }
 catch(Exception e) {

 //here you can treat the possible
 // exceptions thrown by statements
 // execution

 }
 })
.filter(p -> p!=null).collect(Collectors.toList());


//add the new created threads to the list of existing threads

 prgList.addAll(newPrgList);

您不能使用 ExecutorService 转换 Callables 列表。您需要定义 ExecutorService,它将依次获取可调用对象并在一个或多个线程中并行执行它们。

这就是我认为你想要的:

ExecutorService executor = Executors.newCachedThreadPool();//change executor type as per your need.
List<ProgState> newProgList = executor.invokeAll(callList).stream().map(future -> {...

如果可以使用 stream(),为什么不使用 parallelStream(),因为它会简单得多。

 List<PrgState> prgStates = prgList.parallelStream()
                                   .map(p -> p.oneStep())
                                   .collect(Collectors.toList());

这样你就没有线程池来配置,完成后启动或停止。

有些人可能认为 parallelStream() 是将 Stream 和 lambda 表达式添加到 Java 8 的主要原因。 ;)