java并发--Callable的使用

在java并发中提供了Callable<T>的一个接口,可以在线程中返回一个参数,这是接口Runable所做不到的。。

import java.util.ArrayList;
import java.util.Iterator;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class CallableTest {
	/**
	 * 可以返回一个参数
	 * @author Administrator
	 *
	 */
	class TaskCallable implements Callable<String> {
		int id;

		TaskCallable(int id) {
			this.id = id;
		}
		/**
		 * 线程中可以返回一个参数
		 */
		@Override
		public String call() throws Exception {
			return "xxxx" + id;
		}

	}

	public static void main(String[] args) {
		CallableTest test = new CallableTest();
		ArrayList<Future<String>> arrFuture = new ArrayList<Future<String>>();//利用future储存
		ExecutorService executorServer = Executors.newCachedThreadPool();
		try {
			for (int i = 0; i < 10; i++) {
				Future<String> future = executorServer
						.submit(test.new TaskCallable(i));//submit产生futrue对象
				arrFuture.add(future);

			}
			for (Future<String> future : arrFuture) {
				System.out.println(future.get());
			}
		} catch (InterruptedException e) {
			System.out.print(e);
		} catch (ExecutionException e) {
			System.out.print(e);
		} finally {
			executorServer.shutdown();
		}

	}
}

 call函数返回一个参数,跟Runable所不同的是Runable是调用excute(Thread),Callable是调用

submit(Thread).
posted @ 2014-03-18 23:27  菜园的鸟  阅读(2326)  评论(0编辑  收藏  举报