package threadTest; import java.util.ArrayList;
import java.util.Date;
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; /**
*
* 类 描 述: 测试 多线程 实现 callable 带返回值
* 作 者: 赵 鹏
*/
public class FutureTest { @SuppressWarnings("rawtypes")
public static void main(String[] args) throws InterruptedException, ExecutionException { Date date1 = new Date(); //线程池大小
int taskSize = 5; //1创建一个线程池
ExecutorService pool = Executors.newFixedThreadPool(taskSize); //2创建多个砝码绘制的List ArrayList<Future> list = new ArrayList<Future>(); for (int i = 0; i < taskSize; i++) { Callable mCallable = new MCallable(i + "");
//执行任务并获取任务对象
@SuppressWarnings("unchecked")
Future future = pool.submit(mCallable); //System.out.println("【>>>>>】" + future.get().toString());
//将任务对象存入list中
list.add(future);
} //关闭线程组
pool.shutdown(); for (Future future : list) { // 从Future对象上获取任务的返回值,并输出到控制台
System.out.println(">>>" + future.get().toString());
} Date date2 = new Date(); System.out.println("[程序执行完成的花费时间为]" + (date2.getTime()-date1.getTime()) + "毫秒"); } } class MCallable implements Callable<Object> { private String taskNum; MCallable(String taskNum) {
super();
this.taskNum = taskNum;
} @Override
public Object call() throws Exception {
System.out.println(">>> " + taskNum + " 任务开始运行"); Date dateTemp1 = new Date(); Thread.sleep(1000); Date dateTemp2 = new Date(); long time = dateTemp2.getTime() - dateTemp1.getTime(); System.out.println(">>>" +taskNum+ "任务【结束】运行"); return "任务" +taskNum+ "执行完毕 , 运行时间为【" + time +"】毫秒";
} }