package org.tempuri; import java.util.concurrent.*; import java.util.Date; import java.util.List; import java.util.ArrayList; /** * * Java線程:有返回值的線程 * @author wb_qiuquan.ying */ public class Test { @SuppressWarnings("rawtypes") public static void main(String[] args) throws ExecutionException, InterruptedException { int sizeNum = 5; // 建立一個線程池 ExecutorService pool = Executors.newFixedThreadPool(sizeNum); // 建立多個有返回值的任務 List<Future> list = new ArrayList<Future>(); for (int i = 0; i < sizeNum; i++) { // Callable c = new MyCallable(i + " ");也能夠這樣寫,運行結果同樣 MyCallable c = new MyCallable(i + " "); // 執行任務並獲取Future對象 Future f = pool.submit(c); System.out.println("線程運行中此線程的值是:" + f.get().toString()); list.add(f); } // 關閉線程池 pool.shutdown(); // 獲取全部併發任務的運行結果 System.out.println(""); for (Future f : list) { // 從Future對象上獲取任務的返回值,並輸出到控制檯 System.out.println("關閉線程池後,各個線程的值:"+ f.get().toString()); } System.exit(0); } } class MyCallable implements Callable<Object> { private String taskNum; MyCallable(String taskNum) { this.taskNum = taskNum; } //call()方法 public Object call() throws Exception { System.out.println(">>>" + taskNum + "call()方法任務啓動"); Date dateTmp1 = new Date(); Thread.sleep(1000); Date dateTmp2 = new Date(); long time = dateTmp2.getTime() - dateTmp1.getTime(); System.out.println(">>>" + taskNum + "任務終止"); return "線程"+taskNum + "返回運行的時間【" + time + "毫秒】"; } }