我正在处理以下代码示例:

ExecutorService executorService = Executors.newSingleThreadExecutor();

Set<Callable<String>> callables = new HashSet<Callable<String>>();

callables.add(new Callable<String>() {
    public String call() throws Exception {
        return "Task 1";
    }
});
callables.add(new Callable<String>() {
    public String call() throws Exception {
        return "Task 2";
    }
});
callables.add(new Callable<String>() {
    public String call() throws Exception {
        return "Task 3";
    }
});

List<Future<String>> futures = executorService.invokeAll(callables);

for(Future<String> future : futures){
    System.out.println("future.get = " + future.get());
}

executorService.shutdown();

我正在尝试为此代码编写一个包装类,该包装类适用于通用类型,并且在展开时可以转换为String / int / etc。

我遇到的问题是将集合传递给invokeAll()方法。我在将自定义 Activity 添加到可调用集时遇到了一些麻烦。

理想情况下,我希望能够分离出我的代码,以便可以调用方法而不是声明内部类。有没有办法声明从我的自定义方法返回的对象的集合,这些对象可以传递给invokeAll()方法?

我正在尝试一些不同的收藏,但不断得到:
The method invokeAll(Collection<? extends Callable<T>>) in the type ExecutorService is not applicable for the arguments (Collection<Object>)

最佳答案

因为 invokeAll() Generic Method,所以您可能需要使用特殊语法来指示它们的T类型。以下调用应清除您的错误:

List<Future<String>> futures = executorService.<String>invokeAll(callables);

虽然我不得不说,但我能够在一个独立程序中按原样运行您的示例代码...

通常,这不是问题,但是如果使用类型推断定义集合(从Java 7开始可用),则可能会成为问题。例如,如果您通过以下方式初始化了Collection:
Set<Callable<String>> callables = new HashSet<>();

这意味着编译器可能不得不加倍努力才能确定您的集合的类型(尽管这对我来说也是如此)。在您的情况下尤其如此,因为您声称要尝试编写通用包装器类。几乎可以肯定,泛型方法的棘手之处。您可能还需要查看有关通用方法的this Java教程。

10-08 15:29