java獲取執行緒的返回值
阿新 • • 發佈:2019-02-01
import java.util.concurrent.*; /** * Java執行緒:有返回值的執行緒 * * @author Administrator 2009-11-5 0:41:50 */ public class Test { public static void main(String[] args) throws ExecutionException, InterruptedException { //建立一個執行緒池 ExecutorService pool = Executors.newFixedThreadPool(2); //建立兩個有返回值的任務 Callable c1 = new MyCallable("A"); Callable c2 = new MyCallable("B"); //執行任務並獲取Future物件 Future f1 = pool.submit(c1); Future f2 = pool.submit(c2); //從Future物件上獲取任務的返回值,並輸出到控制檯 System.out.println(">>>"+f1.get().toString()); System.out.println(">>>"+f2.get().toString()); //關閉執行緒池 pool.shutdown(); } } class MyCallable implements Callable{ private String oid; MyCallable(String oid) { this.oid = oid; } @Override public Object call() throws Exception { return oid+"任務返回的內容"; } }