1. 程式人生 > >測試 多線程 實現 callable 帶返回值

測試 多線程 實現 callable 帶返回值

logs gettime pri per types object pac color i++

 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 }

測試 多線程 實現 callable 帶返回值