FutureTask類是Future 的一個實現,並實現了Runnable,所以可通過Excutor(線程池) 來執行,也可傳遞給Thread對象執行。如果在主線程中需要執行比較耗時的操作時,但又不想阻塞主線程時,可以把這些作業交給Future對象在后台完成,當主線程將來需要時,就可以通過Future對象獲得后台作業的計算結果或者執行狀態。
Executor框架利用FutureTask來完成異步任務,並可以用來進行任何潛在的耗時的計算。一般FutureTask多用於耗時的計算,主線程可以在完成自己的任務后,再去獲取結果。
FutureTask是一種可以取消的異步的計算任務。它的計算是通過Callable實現的,它等價於可以攜帶結果的Runnable,並且有三個狀態:等待、運行和完成。完成包括所有計算以任意的方式結束,包括正常結束、取消和異常。
Future有個get方法而獲取結果只有在計算完成時獲取,否則會一直阻塞直到任務轉入完成狀態,然后會返回結果或者拋出異常。
FutureTask有下面幾個重要的方法:
1.get()
阻塞一直等待執行完成拿到結果
2.get(int timeout, TimeUnit timeUnit)
阻塞一直等待執行完成拿到結果,如果在超時時間內,沒有拿到拋出異常
3.isCancelled()
是否被取消
4.isDone()
是否已經完成
5.cancel(boolean mayInterruptIfRunning)
試圖取消正在執行的任務
demo1:
package net.jcip.examples; import java.util.Random; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; /** * * @author Administrator * */ @SuppressWarnings("all") public class FutureTaskDemo { public static void main(String[] args) { // 初始化一個Callable對象和FutureTask對象 Callable pAccount = new PrivateAccount(); FutureTask futureTask = new FutureTask(pAccount); // 使用futureTask創建一個線程 Thread pAccountThread = new Thread(futureTask); System.out.println("futureTask線程現在開始啟動,啟動時間為:" + System.nanoTime()); pAccountThread.start(); System.out.println("主線程開始執行其他任務"); // 從其他賬戶獲取總金額 int totalMoney = new Random().nextInt(100000); System.out.println("現在你在其他賬戶中的總金額為" + totalMoney); System.out.println("等待私有賬戶總金額統計完畢..."); // 測試后台的計算線程是否完成,如果未完成則等待 while (!futureTask.isDone()) { try { Thread.sleep(500); System.out.println("私有賬戶計算未完成繼續等待..."); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("futureTask線程計算完畢,此時時間為" + System.nanoTime()); Integer privateAccountMoney = null; try { privateAccountMoney = (Integer) futureTask.get(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } System.out.println("您現在的總金額為:" + totalMoney + privateAccountMoney.intValue()); } } @SuppressWarnings("all") class PrivateAccount implements Callable { Integer totalMoney; @Override public Object call() throws Exception { Thread.sleep(5000); totalMoney = new Integer(new Random().nextInt(10000)); System.out.println("您當前有" + totalMoney + "在您的私有賬戶中"); return totalMoney; } }
demo2:
package net.jcip.examples; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; public class FutureTaskSample { static FutureTask<String> future = new FutureTask(new Callable<String>(){ public String call(){ return getPageContent(); } }); public static void main(String[] args) throws InterruptedException, ExecutionException{ //Start a thread to let this thread to do the time exhausting thing new Thread(future).start(); //Main thread can do own required thing first System.out.println(doOwnThing()); //At the needed time, main thread can get the result // while(future.isDone()) for(;;){ if(future.isDone()){ System.out.println(future.get()); break; }else System.out.println("waiting………………"); } } public static String doOwnThing(){ return "Do Own Thing"; } public static String getPageContent(){ try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } return "testPageContent and provide that the operation is a time exhausted thing..."; } }
(原文地址:http://blog.csdn.net/bbgb1984/article/details/8471873)