在流中使用Executor服务时,我遇到了编译时错误。 (还有其他方法,但我想检查一下是否可行)
class Operation implements Callable<Integer> {
int i; int j;
Operation(int i, int j) { this.i = i; this.j = j; }
@Override
public Integer call() {
return integerOps(i, j); //integerOps throws MyException
}
}
// somewhere within main method
total = IntStream
.range(1,100)
.boxed()
.map(t -> executor.submit(new Operation(t, FACTOR) )) // -> COMPILE TIME ERROR
.map(t -> {
try {
return t.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return 0;
})
.mapToInt(t->t)
.sum();
案例1:
如果MyException
为RuntimeException
(未选中),则错误为
无法访问类型
IterativeExecutionTechniques
的封闭实例。必须使用IterativeExecutionTechniques
类型的封闭实例限定分配(例如x.new A()
,其中x
是IterativeExecutionTechniques
的实例。
如何在不触及Operation类的情况下解决这个问题,以及如何使未经检查的异常中断执行并正常退出?
案例2:
如果MyException
为Exception
(已选中),则错误为
无法访问类型
ExceptionHandling
的封闭实例。必须使用ExceptionHandling
类型的封闭实例限定分配(例如x.new A()
,其中x
是ExceptionHandling
的实例。
如何在不触及Operation类的情况下解决这个问题,以及如何处理已检查的异常并继续执行?