java.util.concurrent.Future淺析

來源:互聯網
上載者:User

        在學習多線程的時候,看到了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();}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.