在學習多線程的時候,看到了Future這個介面,學習了一下,記錄下來。
Future介面是一個泛型介面,嚴格來說是Future<V>。Future一般用於比較耗時的操作,但不處理又不行,那麼就可以把這個任務交給Future來處理,我們可以做其他的事情,等Future處理好這個耗時的任務後,會返回給我們處理後資訊。具體的實作類別為java.util.concurrent.FutureTask<V>。
jdk中的描述是:
A Future represents the result of an asynchronous computation. Methods are provided to check if the computation is complete, to wait for its completion, and to retrieve the result of the computation. The result can only be retrieved using
method get when the computation has completed, blocking if necessary until it is ready. Cancellation is performed by thecancel method. Additional methods are provided to determine if the task completed normally or was cancelled. Once a computation
has completed, the computation cannot be cancelled. If you would like to use aFuture for the sake of cancellability but not provide a usable result, you can declare types of the formFuture<?> and return
null as a result of the underlying task.
翻譯出來就是:
Future 表示非同步計算的結果。它提供了檢查計算是否完成的方法,以等待計算的完成,並擷取計算的結果。計算完成後只能使用 get 方法來擷取結果,如有必要,計算完成前可以阻塞此方法。取消則由cancel 方法來執行。還提供了其他方法,以確定任務是正常完成還是被取消了。一旦計算完成,就不能再取消計算。如果為了可取消性而使用
Future 但又不提供可用的結果,則可以聲明Future<?> 形式類型、並返回 null 作為底層任務的結果。
網上的例子比較好,我就摘抄過來了,請作者見諒:
package com.bao.study;import java.util.concurrent.Callable;import java.util.concurrent.ExecutionException;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;public class TestFutureTask {public static void main(String[] args) throws InterruptedException,ExecutionException {final ExecutorService exec = Executors.newFixedThreadPool(5);Callable<String> call = new Callable<String>() {public String call() throws Exception {Thread.sleep(1000 * 3);//休眠指定的時間,此處表示該操作比較耗時return "Other less important but longtime things.";}};Future<String> task = exec.submit(call);//重要的事情Thread.sleep(1000 * 3);System.out.println("Let's do important things.");//不重要的事情String obj = task.get();System.out.println(obj);//關閉線程池exec.shutdown();}}