- Future代表一個(gè)異步計(jì)算的結(jié)果武花,并且它提供一些方法來讓調(diào)用者檢測(cè)異步過程是否完成沧竟,或者取得異步計(jì)算的結(jié)果铸敏,或者取消正在執(zhí)行的異步任務(wù)。*
public class Test {
private static ExecutorService executorService = Executors.newSingleThreadExecutor();
public static void main(String[]args){
System.out.println("hello world");
Future<Integer>future = calcute(9);
while (!future.isDone()){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
System.out.println("正在執(zhí)行");
}
}
try {
int result = future.get();
System.out.println("result = " + result);
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static Future<Integer>calcute(Integer i) {
return executorService.submit(() -> {
Thread.sleep(1000);
System.out.println("return future for " + i);
return i *i;
});
}
}
一個(gè)簡(jiǎn)單Future使用用例寫完悟泵,使用線程池+Callback+Future杈笔,完成了一個(gè)簡(jiǎn)單的計(jì)算操作。
Future是一個(gè)接口糕非,先看一下內(nèi)部方法:
public interface Future<V> {
boolean cancel(boolean var1);
boolean isCancelled();
boolean isDone();
V get() throws ExecutionException, InterruptedException;
V get(long var1, TimeUnit var3) throws ExecutionException, InterruptedException, TimeoutException;
}
get()函數(shù)是返回計(jì)算結(jié)果蒙具,注意get會(huì)同步操作,沒有返回結(jié)果前朽肥,會(huì)阻塞線程禁筏。
get還有一個(gè)重載函數(shù)get(long var1, TimeUnit var3),第一個(gè)參數(shù)是時(shí)長(zhǎng)衡招,第二個(gè)是單位篱昔。
表示在多少時(shí)長(zhǎng)內(nèi)獲取結(jié)果,如果仍未返回始腾,則拋出異常TimeoutException州刽。
try{
int result2 = future2.get(1000, TimeUnit.MILLISECONDS);
} catch(TimeoutException e) {
e.printStackTrace();
}
cancel(boolean) 表示是否取消該future,
不能在調(diào)用cancel(true)/cancel(false)后浪箭,調(diào)用get()函數(shù)穗椅,否則會(huì)拋出異常CancellationException
isCancelled()函數(shù)是判斷該future是否已取消
isDone()函數(shù)是判斷該future是否已完成
isDone()函數(shù)是實(shí)時(shí)狀態(tài)讀取,不會(huì)阻塞線程奶栖。
Callback
Callback 是一個(gè)接口房待,內(nèi)部只有一個(gè)函數(shù)
@FunctionalInterface
public interface Callable<V> {
V call() throws Exception;
}