簡介
這個思想來源於Future設計模式:https://blog.csdn.net/qq_43040688/article/details/105868293
public interface Callable<V> {
V call() throws Exception;
}
可以看到,這是一個泛型接口,該接口聲明瞭一個名稱爲call()的方法,同時這個方法可以有返回值V,也可以拋出異常。call()方法返回的類型就是傳遞進來的V類型。
那麼怎麼使用Callable呢?一般情況下是配合ExecutorService來使用的,在ExecutorService接口中聲明瞭若干個submit方法的重載版本。
API
獲取結果
V get()throws InterruptedException, ExecutionException
V get(long timeout,TimeUnit unit)
throws InterruptedException, ExecutionException,TimeoutException
- 這是個阻塞的方法,會阻塞調用者
- 如果設置時間,會阻塞一段時間,如果沒有獲得到結果,就會拋出異常
查看任務是否完成
boolean isDone()
有三成情況會出現完成
- 正常執行完成
- 出現異常
- 被取消掉
取消任務
boolean cancel(boolean mayInterruptIfRunning)
- 如果任務沒有啓動,會被取消掉
- 如果任務啓動,
mayInterruptIfRunning
爲true,也會被取消 - 執行該方法後
isDone
將一直返回true
注意:該方法執行的依然是Interrupt
,如果任務執行時間很長,依然需要使用守護線程方式關閉