我们可以从Java中的Future对象获取Callable对象吗?

问题描述 投票:1回答:2

我有一个可调用对象列表,我用它来生成未来对象列表。我正在使用ExecutorService来同时完成Callable任务并将结果存储为Future对象的列表。现在我想知道,有没有办法让我可以获得用于生成给定未来对象的原始可调用对象。

java future executorservice java.util.concurrent callable
2个回答
1
投票

如果您通过调用Future获得ExecutorService.invokeAll()s,您可以依赖于javadoc中记录的订单。

 * @return a list of Futures representing the tasks, in the same
 *         sequential order as produced by the iterator for the
 *         given task list, each of which has completed

0
投票

虽然您可以创建自己的callable,但默认实现并未提供此功能

   import org.apache.commons.math3.util.Pair;

    class MyCallable implements Callable<Pair<Callable,MyObject>>{

        private MyService service;
        public String name;
        public MyCallable(MyService srevice,String name){
            this.srevice = srevice;
            this.name = name;

        }

        @Override
        public Pair<Callable,MyObject> call() throws Exception {
            return new Pair(this,service.doSomeStuff())
        }
    }

现在,当您将来调用可调用对象时,您将可以访问可调用对象。像future.get().getFirst().name这样的东西会起作用。

© www.soinside.com 2019 - 2024. All rights reserved.