Java 5 前線程無返回值,需通過共享變量、回調等繞道。Java 5 引入 Callable 接口:
V call() throws Exception:有返回值、可拋異常Future 獲取結果:get() 阻塞等待完成ExecutorService.submit(Callable) 返回 Futureimport java.util.concurrent.*;
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 f1 = pool.submit(c1);
Future f2 = pool.submit(c2);
System.out.println(">>>" + f1.get()); // 阻塞獲取結果
System.out.println(">>>" + f2.get());
pool.shutdown();
}
}
class MyCallable implements Callable {
private String oid;
MyCallable(String oid) { this.oid = oid; }
@Override public String call() throws Exception {
return oid + "任務返回的內容";
}
}
>>A任務返回的內容
>>>B任務返回的內容
Process finished with exit code 0
get():阻塞直到結果就緒get(long timeout, TimeUnit unit):超時獲取,防死等cancel(boolean mayInterruptIfRunning):嘗試取消任務isDone():判斷是否完成isCancelled():判斷是否被取消get() 收割結果invokeAll() 等待全部完成,invokeAny() 等待任一完成get() 拋出 ExecutionException 包裝任務異常,InterruptedException 當前線程被中斷shutdown() 線程池,避免資源洩漏get() 無限阻塞