多线程之Callable

来源:互联网 发布:淘宝优惠券shipinwj 编辑:程序博客网 时间:2024/06/08 08:53

To demonstrate, the following example creates separate Callable instances for each word passed in on the command line and sums up their length. Each Callable will just calculate the sum of its individual word. The set of Future objects are saved to acquire the calculated value from each. If the order of the returned values needed to be preserved, a List could be used instead.

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);  }}
The WordLengthCallable saves each word and uses the word's length as the value returned by the call() method. This value could take some time to generate but in this case is known immediately. The only requirement of call() is the value is returned at the end of the call. When the get() method of Future is later called, the Future will either have the value immediately if the task runs quickly, as in this case, or will wait until the value is done generating. Multiple calls to get() will not cause the task to be rerun in the thread.

原文:https://blogs.oracle.com/CoreJavaTechTips/entry/get_netbeans_6

原创粉丝点击