从列表List <future <callable <integer >>>

时间:2019-05-13 10:45:55

标签: java multithreading

任务: 您将获得返回Callable的Future对象的列表。您应该从列表的末尾开始以相反的顺序执行这些Callable对象,并返回这些Callable对象返回的值的总和。

实施方法:

导入java.util.concurrent。*;

class FutureUtils {

    public static int executeCallableObjects(List<Future<Callable<Integer>>> items) {
        // write your code here
    }

}

所以,问题是如何正确检索可调用任务的结果

我的理解:

1)为了提交Callable,我们需要使用

ExecutorService exec = Executors.newFixedThreadPool(4); exec.submit(put Callable);

2)为了检索Callable执行的结果,我们需要使用Future对象;

我了解如何从Callable列表而不是>>

中检索结果

我相信我想念一些东西。

这是我编写的试图理解如何完成任务的代码


  public static void main(String[] args) throws InterruptedException, IOException {

        ExecutorService executorService = Executors.newFixedThreadPool(4);

        List<Future<Callable<Integer>>> list = new ArrayList<>();

        Future first = executorService.submit(new PrintIfPrimeTask(1));
        list.add(first);

        try {
            ExecutorService exec = Executors.newFixedThreadPool(4);
            Future<Callable<Integer>> good = list.get(0);
        Callable<Integer> temp = good.get();
       Future<Integer> kek = exec.submit(temp);

      Integer a = (Integer) kek.get();
            System.out.println(a);


        } catch (Throwable e) {
            e.printStackTrace();
        }
        executorService.shutdown();

    }
}

它给

java.lang.ClassCastException: java.base/java.lang.Integer cannot be cast to java.base/java.util.concurrent.Callable
    at Solution.main(Solution.java:36)

PrintIfPrimeTask除了返回2之外什么都不做

class PrintIfPrimeTask implements Callable<Integer> {
    private final int number;

    public PrintIfPrimeTask(int number){
        this.number = number;
    }

    @Override
    public Integer call() throws Exception {
        return 2;
    }
}

0 个答案:

没有答案