时间:2018-02-12 19:20:36

标签: java multithreading java-stream executorservice

在流中使用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:

如果MyExceptionRuntimeException(未选中),则错误为

  

无法访问类型IterativeExecutionTechniques的封闭实例。必须使用IterativeExecutionTechniques类型的封闭实例限定分配(例如x.new A(),其中xIterativeExecutionTechniques的实例。

如何在不触及Operation类的情况下解决这个问题,以及如何使未经检查的异常中断执行并正常退出?

案例2:

如果MyExceptionException(已选中),则错误为

  

无法访问类型ExceptionHandling的封闭实例。必须使用ExceptionHandling类型的封闭实例限定分配(例如x.new A(),其中xExceptionHandling的实例。

如何在不触及Operation类的情况下解决这个问题,以及如何处理已检查的异常并继续执行?

0 个答案:

没有答案