欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

java使用Callable接口的多线程例子,callable多线程,//http://blo

来源: javaer 分享于  点击 14175 次 点评:112

java使用Callable接口的多线程例子,callable多线程,//http://blo


//http://blogs.oracle.com/CoreJavaTechTips/entry/get_netbeans_6import 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);  }}
相关栏目:

用户点评