【发布时间】:2022-01-03 01:19:04
【问题描述】:
我正在使用执行器服务来并行运行任务。并行运行方法接受输入整数并返回整数。由于并行任务有返回类型,所以我使用了 Callable 匿名类。您可以在下面的示例中看到 ExecutorServiceExample task(int i ) 是从 executer 调用的。任务方法也有1秒的等待时间并抛出i==7;的异常
在下面的实现中,我使用 invokeAll 并使用 isDone 并尝试收集数据。
下面的程序抛出IllegalMonitorStateException。
Future 任务迭代和检查 isDone 和 get() 有什么问题。如何处理特定调用的异常。我想并行运行所有 1 到 14 个任务,并在所有完成时收集返回返回类型。此外,如果出现错误,如何知道它抛出异常的输入,例如(7 和 14)
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.*;
import java.util.stream.Collectors;
class MyException extends Exception{
MyException(String message) {
super(message);
}
}
public class ExecutorServiceExample {
public int task(int i) throws MyException, InterruptedException {
System.out.println("Running task.."+i);
wait(1000);
if(i%7==0) {
throw new MyException("multiple of 7 not allowed");
}
return i;
}
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(10);
List<Callable<Integer>> tasks = Arrays.asList(1,2,3,4,5,6,7,8,9,10,11,12,13,14).stream().map(id->{
return new Callable<Integer>() {
@Override
public Integer call() throws Exception {
ExecutorServiceExample executorServiceExample = new ExecutorServiceExample();
return executorServiceExample.task(id);
}
};
}).collect(Collectors.toList());
try{
List<Future<Integer>> results = executorService.invokeAll(tasks);
for (Future<Integer> task: results) {
if(task.isDone()){
System.out.println(task.get());
}
}
}catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}finally {
executorService.shutdown();
}
}
}
【问题讨论】:
标签: java multithreading collections threadpool java-threads