gpt4 book ai didi

java - 通过 ExecutorCompletionService 中的 Callable 获取 Future

转载 作者:行者123 更新时间:2023-12-01 11:24:03 25 4
gpt4 key购买 nike

在我的应用程序中,我的任务已实现 Callable提交至ExecutorCompletionService并返回Future实例存储在List中。然后那些Future实例一一检索如下。

        List<Future< Object>> futureList= new ArrayList<Future < Object> >();

final ExecutorService pool = Executors.newFixedThreadPool( TASK_SIZE );

final ExecutorCompletionService<Object> completionService = new ExecutorCompletionService<Object> (pool);
for ( AbstractTask callable : taskList) {
futureList.add( completionService.submit(callable) );
}
Object rv=null;
while(futureList.size() > 0) {
try{
Future ft = completionService.take();
rv = ft.get();
System.out.println("task returned value : " + rv);
futureList.remove(ft);
}catch(Exception e){
e.printStackTrace();
}
}

这里,打印从 rv = ft.get(); 返回的每个 AbstractTask 的输出。 。但我想要一种方法来获取 AbstractTask 以及返回值。有没有办法获取 Callable 的名称(在我的例子中为 AbstractTask),它在 Future.get() 时返回值?

最佳答案

您只需填充 Map<Future<Object>, AbstractTask>将每个 Future 与“创建”它的任务相关联。

完整示例:

public class Tasks {
public static void main(String[] args) throws InterruptedException {
ExecutorCompletionService<String> service = new ExecutorCompletionService<String>(Executors.newSingleThreadExecutor());

List<Callable<String>> callables = new ArrayList<>();
Map<Future<String>, Callable<String>> map = new HashMap<>();

for (int i = 0; i < 10; i++) {
final String name = Integer.toString(i);
Callable<String> c = new Callable<String>() {
@Override
public String call() throws Exception {
return name;
}

@Override
public String toString() {
return name;
}
};
callables.add(c);

Future<String> future = service.submit(c);
map.put(future, c);
}

for (int i = 0; i < callables.size(); i++) {
Future<String> future = service.take();
Callable<String> correspondingTask = map.get(future);
System.out.println("correspondingTask = " + correspondingTask);
}
}
}

关于java - 通过 ExecutorCompletionService 中的 Callable 获取 Future,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30966788/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com