【问题标题】:usage of generic in Callable and Future interface?在 Callable 和 Future 接口中使用泛型?
【发布时间】:2014-09-29 22:25:46
【问题描述】:

Callable接口中泛型有什么用?

考虑一下我从https://blogs.oracle.com/CoreJavaTechTips/entry/get_netbeans_6复制的这段代码:

import java.util.\*;
import java.util.concurrent.\*;

public class CallableExample {

  public static class WordLengthCallable
        implements Callable {
    private String word;
    public WordLengthCallable(String word) {
      this.word = word;
    }
    public Integer call() {
      return Integer.valueOf(word.length());
    }
  }

  public static void main(String args[]) throws Exception {
    ExecutorService pool = Executors.newFixedThreadPool(3);
    Set<Future<Integer>> set = new HashSet<Future<Integer>>();
    for (String word: args) {
      Callable<Integer> callable = new WordLengthCallable(word);
      Future<Integer> future = pool.submit(callable);
      set.add(future);
    }
    int sum = 0;
    for (Future<Integer> future : set) {
      sum += future.get();
    }
    System.out.printf("The sum of lengths is %s%n", sum);
    System.exit(sum);
  }
}

Callable&lt;Integer&gt;Future&lt;Integer&gt; 中的整数未被使用。它也可以是其他任何东西,例如 Callable&lt;String&gt;Future&lt;String&gt;,并且代码仍然可以工作。

我了解泛型的用法,并特别欣赏它在集合中的用法。

谢谢。

【问题讨论】:

  • 这样get 将返回Integer 而不是Object,还是我错了?

标签: java multithreading generics concurrency callable


【解决方案1】:

CallableRunnable 的区别在于Callable 中返回值的能力(如果使用ExecutorService,则可通过Future 检索)。他们本可以将其编码为仅返回 Object 并进行代码转换,但绝对不会有编译时检查。使Callable 泛型来指定返回类型似乎是合乎逻辑的,这样您就不需要显式转换并且可以进行编译时检查。

当然,由于类型擦除,这一切都会在运行时消失,但这并不会降低其价值 WRT 意图和编译时间。

【讨论】:

  • 而且,它避免你捕获检查异常
  • 我的错,它与集合中的逻辑相同,不知何故我以前无法理解它。感谢您的回答。
  • 那么为什么Runnable 也带有泛型?
  • @BasilBourque Runnable 不是通用的。请注意,在 java 文档中它是 Runnable 而不是 Runnable&lt;T&gt;。作为对比Callable
【解决方案2】:

约翰给出了一个正确的答案。只是增加了不的重要性 忽略编译器警告。在编译您当前的代码时,编译器会警告您unchecked conversion

$ javac -Xlint:unchecked CallableExample.java
CallableExample.java:22: warning: [unchecked] unchecked conversion
found   : CallableExample.WordLengthCallable
required: java.util.concurrent.Callable<java.lang.Integer>
            Callable<Integer> callable = new WordLengthCallable(word);
                                         ^
1 warning

Callable&lt;Integer&gt;Future&lt;Integer> 中的整数未被使用。它 也可以是其他任何东西,例如 Callable&lt;String&gt;Future&lt;String&gt; 和代码仍然可以工作。

更改您的班级以使用implements Callable&lt;Integer&gt;

如果您开始在任何地方使用Callable&lt;String&gt;Future&lt;String&gt;,编译器会很高兴,您的代码将无法工作。

【讨论】:

    猜你喜欢
    • 2016-02-15
    • 1970-01-01
    • 1970-01-01
    • 2013-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多