java多線程獲取返回結果--Callable和Future示例

 1 package test.guyezhai.thread;
 2 
 3 import java.util.ArrayList;
 4 import java.util.Date;
 5 import java.util.List;
 6 import java.util.concurrent.Callable;
 7 import java.util.concurrent.ExecutionException;
 8 import java.util.concurrent.ExecutorService;
 9 import java.util.concurrent.Executors;
10 import java.util.concurrent.Future;
11 
12 @SuppressWarnings("unchecked")
13 public class TestThread {
14 
15     @SuppressWarnings("rawtypes")
16     public static void main(String[] args) throws ExecutionException, InterruptedException {
17         System.out.println("----程序開始運行----");
18         Date date1 = new Date();
19 
20         int taskSize = 50000;
21         // 建立一個線程池
22         ExecutorService pool = Executors.newFixedThreadPool(taskSize);
23         // 建立多個有返回值的任務
24         List<Future> list = new ArrayList<Future>();
25         for (int i = 0; i < taskSize; i++) {
26             Callable c = new MyCallable(i + " ");
27             // 執行任務並獲取Future對象
28             Future f = pool.submit(c);
29             // System.out.println(">>>" + f.get().toString());
30             list.add(f);
31         }
32         // 關閉線程池
33         pool.shutdown();
34 
35         // 獲取全部併發任務的運行結果
36         for (Future f : list) {
37             // 從Future對象上獲取任務的返回值,並輸出到控制檯
38             System.out.println(">>>" + f.get().toString());
39         }
40 
41         Date date2 = new Date();
42         System.out.println("----程序結束運行----,程序運行時間【" + (date2.getTime() - date1.getTime()) + "毫秒】");
43     }
44 }
45 
46 class MyCallable implements Callable<Object> {
47     private String taskNum;
48 
49     MyCallable(String taskNum) {
50         this.taskNum = taskNum;
51     }
52 
53     @Override
54     public Object call() throws Exception {
55         System.out.println(">>>" + taskNum + "任務啓動");
56         Date dateTmp1 = new Date();
57         Thread.sleep(1000);
58         Date dateTmp2 = new Date();
59         long time = dateTmp2.getTime() - dateTmp1.getTime();
60         System.out.println(">>>" + taskNum + "任務終止");
61         return taskNum + "任務返回運行結果,當前任務時間【" + time + "毫秒】";
62     }
63 }
相關文章
相關標籤/搜索