ITeye博客

可管理线程demo

xxtianxiaxing · 2009-08-12 12:54 · java thread · Markdown


package test;

import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * 此类描述的是:
 * 
 * @author 作者 E-mail: wangxiongdx@163.com
 * @version 创建时间:2009-8-12 上午11:46:32
 */
public class CallableExample {
	public static class WordLengthCallable implements Callable<Integer> {
		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.println("--->"+args[0]);
		System.out.printf("The sum of lengths is %s%n", sum);
		System.exit(sum);
	}
}






评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。