首页 > 技术文章 > 测试 多线程 实现 callable 带返回值

zhao-blog 2017-07-11 12:34 原文

 1 package threadTest;
 2 
 3 import java.util.ArrayList;
 4 import java.util.Date;
 5 import java.util.concurrent.Callable;
 6 import java.util.concurrent.ExecutionException;
 7 import java.util.concurrent.ExecutorService;
 8 import java.util.concurrent.Executors;
 9 import java.util.concurrent.Future;
10 
11 /**
12  * 
13  * 类  描  述: 测试 多线程 实现 callable 带返回值
14  * 作        者: 赵         鹏
15  */
16 public class FutureTest {
17 
18     @SuppressWarnings("rawtypes")
19     public static void main(String[] args) throws InterruptedException, ExecutionException {
20         
21         Date date1 = new Date();
22         
23         //线程池大小
24         int taskSize = 5;
25         
26         //1创建一个线程池
27         ExecutorService pool = Executors.newFixedThreadPool(taskSize);
28         
29         //2创建多个砝码绘制的List
30         
31         ArrayList<Future> list = new ArrayList<Future>();
32         
33         for (int i = 0; i < taskSize; i++) {
34             
35             Callable mCallable = new MCallable(i + "");
36             //执行任务并获取任务对象
37             @SuppressWarnings("unchecked")
38             Future future = pool.submit(mCallable);
39             
40             //System.out.println("【>>>>>】" + future.get().toString());
41             //将任务对象存入list中
42             list.add(future);
43         }
44         
45         //关闭线程组
46         pool.shutdown();
47         
48         for (Future future : list) {
49             
50             // 从Future对象上获取任务的返回值,并输出到控制台  
51             System.out.println(">>>" + future.get().toString());  
52         }
53         
54         Date date2 = new Date();
55         
56         System.out.println("[程序执行完成的花费时间为]" + (date2.getTime()-date1.getTime()) + "毫秒");
57         
58     }
59     
60 }
61 
62 
63 class MCallable implements Callable<Object> {
64 
65     private String taskNum;
66     
67     MCallable(String taskNum) {
68         super();
69         this.taskNum = taskNum;
70     }
71     
72     @Override
73     public Object call() throws Exception {
74         System.out.println(">>> " + taskNum + " 任务开始运行");
75         
76         Date dateTemp1 = new Date();
77         
78         Thread.sleep(1000);
79         
80         Date dateTemp2 = new Date();
81         
82         long time = dateTemp2.getTime() - dateTemp1.getTime();
83         
84         System.out.println(">>>" +taskNum+ "任务【结束】运行");
85         
86         return "任务" +taskNum+ "执行完毕  , 运行时间为【" + time +"】毫秒";
87     }
88     
89     
90     
91 }

 

推荐阅读