一、例子:
package com.cy.test.concurrent; import com.google.common.collect.Lists; import java.util.List; import java.util.concurrent.*; /** * 测试future Task */ public class FutureTest { private static ExecutorService pool = Executors.newFixedThreadPool(5); public static void main(String[] args) { List<FutureTask<String>> taskList = Lists.newArrayList(); for(int i=0; i<5; i++){ final int temp = i; FutureTask<String> future = new FutureTask<String>(new Callable<String>() { @Override public String call() throws Exception { Thread.sleep(3000); return "zhangsan" + temp; } }); //pool.execute(future); new Thread(future).start(); taskList.add(future); } List<String> nameList = Lists.newArrayList(); for(FutureTask<String> future : taskList){ try { nameList.add(future.get()); } catch (Exception e) { e.printStackTrace(); } } System.out.println(nameList); } }
console输出:
[zhangsan0, zhangsan1, zhangsan2, zhangsan3, zhangsan4]
二、可以参考这篇博客对future、callable的说明:http://www.cnblogs.com/dolphin0520/p/3949310.html