java併發編程-Future與FutureTask

API:
Java代碼
public interface Executor {       
     void execute(Runnable command);     
 }    
   
 public interface ExecutorService extends Executor {     
      
     <T> Future<T> submit(Callable<T> task);          
     <T> Future<T> submit(Runnable task, T result);       
     Future<?> submit(Runnable task);           
     ...        
 }     
   
 public class FutureTask<V>  extends Object     
             implements Future<V>, Runnable    
 FutureTask(Callable<V> callable)      
       //創建一個 FutureTask,一旦運行就執行給定的 Callable。       
 FutureTask(Runnable runnable, V result)      
       //創建一個 FutureTask,一旦運行就執行給定的 Runnable,並安排成功完成時 get 返回給定的結果 。     
   
 /*參數:    
 runnable - 可運行的任務。    
 result - 成功完成時要返回的結果。    
 如果不需要特定的結果,則考慮使用下列形式的構造:Future<?> f = new FutureTask<Object>(runnable, null)  */  
如果不需要特定的結果,則考慮使用下列形式的構造:Future<?> f = new FutureTask<Object>(runnable, null)  */
 FutureTask多用於耗時的計算,主線程可以在完成自己的任務後,再去獲取結果。
 
單獨使用Runnable時:
        無法獲得返回值
 
單獨使用Callable時:
        無法在新線程中(new Thread(Runnable r))使用,只能使用ExecutorService
        Thread類只支持Runnable
 
FutureTask:
         實現了Runnable和Future,所以兼顧兩者優點
         既可以使用ExecutorService,也可以使用Thread
 
Java代碼
Callable pAccount = new PrivateAccount();     
     FutureTask futureTask = new FutureTask(pAccount);     
     // 使用futureTask創建一個線程     
     Thread thread = new Thread(futureTask);     
     thread.start();    
Callable pAccount = new PrivateAccount(); 
FutureTask futureTask = new FutureTask(pAccount); 
// 使用futureTask創建一個線程 
Thread thread = new Thread(futureTask); 
thread.start(); 

 
 
=================================================================
public interface Future<V> Future 表示異步計算的結果。
Future有個get方法而獲取結果只有在計算完成時獲取,否則會一直阻塞直到任務轉入完成狀態,然後會返回結果或者拋出異常。 
 
FutureTask是爲了彌補Thread的不足而設計的,它可以讓程序員準確地知道線程什麼時候執行完成並獲得到線程執行完成後返回的結果(如果有需要)。
 
FutureTask是一種可以取消的異步的計算任務。它的計算是通過Callable實現的,它等價於可以攜帶結果的Runnable,並且有三個狀態:等待、運行和完成。完成包括所有計算以任意的方式結束,包括正常結束、取消和異常。
 
Future 主要定義了5個方法: 

1)boolean cancel(boolean mayInterruptIfRunning):試圖取消對此任務的執行。如果任務已完成、或已取消,或者由於某些其他原因而無法取消,則此嘗試將失敗。當調用 cancel 時,如果調用成功,而此任務尚未啓動,則此任務將永不運行。如果任務已經啓動,則 mayInterruptIfRunning 參數確定是否應該以試圖停止任務的方式來中斷執行此任務的線程。此方法返回後,對 isDone() 的後續調用將始終返回 true。如果此方法返回 true,則對 isCancelled() 的後續調用將始終返回 true。 

2)boolean isCancelled():如果在任務正常完成前將其取消,則返回 true。 
3)boolean isDone():如果任務已完成,則返回 true。 可能由於正常終止、異常或取消而完成,在所有這些情況中,此方法都將返回 true。 
4)V get()throws InterruptedException,ExecutionException:如有必要,等待計算完成,然後獲取其結果。 
5)V get(long timeout,TimeUnit unit) throws InterruptedException,ExecutionException,TimeoutException:如有必要,最多等待爲使計算完成所給定的時間之後,獲取其結果(如果結果可用)。
 
Java代碼
public class FutureTask<V>  extends Object   
     implements Future<V>, Runnable  
public class FutureTask<V>  extends Object
implements Future<V>, Runnable FutureTask類是Future 的一個實現,並實現了Runnable,所以可通過Excutor(線程池) 來執行,也可傳遞給Thread對象執行。如果在主線程中需要執行比較耗時的操作時,但又不想阻塞主線程時,可以把這些作業交給Future對象在後臺完成,當主線程將來需要時,就可以通過Future對象獲得後臺作業的計算結果或者執行狀態。 
Executor框架利用FutureTask來完成異步任務,並可以用來進行任何潛在的耗時的計算。一般FutureTask多用於耗時的計算,主線程可以在完成自己的任務後,再去獲取結果。
 
JDK:
此類提供了對 Future 的基本實現。僅在計算完成時才能檢索結果;如果計算尚未完成,則阻塞 get 方法。一旦計算完成,就不能再重新開始或取消計算。
 
可使用 FutureTask 包裝 Callable 或 Runnable 對象。因爲 FutureTask 實現了 Runnable,所以可將 FutureTask 提交給 Executor 執行。
 
 
Java代碼
構造方法摘要   
 FutureTask(Callable<V> callable)    
           創建一個 FutureTask,一旦運行就執行給定的 Callable。   
   
 FutureTask(Runnable runnable, V result)    
           創建一個 FutureTask,一旦運行就執行給定的 Runnable,並安排成功完成時 get 返回給定的結果 。   
 參數:   
 runnable - 可運行的任務。   
 result - 成功完成時要返回的結果。   
 如果不需要特定的結果,則考慮使用下列形式的構造:Future<?> f = new FutureTask<Object>(runnable, null)  
構造方法摘要
FutureTask(Callable<V> callable)
          創建一個 FutureTask,一旦運行就執行給定的 Callable。

FutureTask(Runnable runnable, V result)
          創建一個 FutureTask,一旦運行就執行給定的 Runnable,並安排成功完成時 get 返回給定的結果 。
參數:
runnable - 可運行的任務。
result - 成功完成時要返回的結果。
如果不需要特定的結果,則考慮使用下列形式的構造:Future<?> f = new FutureTask<Object>(runnable, null)
 
Example1:
下面的例子模擬一個會計算賬的過程,主線程已經獲得其他帳戶的總額了,爲了不讓主線程等待 PrivateAccount類的計算結果的返回而啓用新的線程去處理, 並使用 FutureTask對象來監控,這樣,主線程還可以繼續做其他事情, 最後需要計算總額的時候再嘗試去獲得privateAccount 的信息。 
 
Java代碼
package test;   
   
 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;   
     }   
   
 }  
package test;

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;
}

}

 運行結果   

 
 來源:
http://zheng12tian.iteye.com/blog/991484
  
Example2:
Java代碼
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   
         doOwnThing();   
   
         //At the needed time, main thread can get the result   
         System.out.println(future.get());   
     }   
        
     public static String doOwnThing(){   
         return "Do Own Thing";   
     }   
     public static String getPageContent(){   
         return "Callable method...";   
     }   
 }  
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
        doOwnThing();

        //At the needed time, main thread can get the result
        System.out.println(future.get());
    }

    public static String doOwnThing(){
        return "Do Own Thing";
    }
    public static String getPageContent(){
        return "Callable method...";
    }
} 結果爲:Callable method...
來源:http://tomyz0223.iteye.com/blog/1019924
 改爲這樣,結果就正常:
Java代碼
public class FutureTaskSample {     
          
     public static void main(String[] args) throws InterruptedException, ExecutionException{     
         //Start a thread to let this thread to do the time exhausting thing     
         Callable call = new MyCallable();   
         FutureTask future = new FutureTask(call);   
         new Thread(future).start();     
      
         //Main thread can do own required thing first     
         //doOwnThing();     
         System.out.println("Do Own Thing");     
            
         //At the needed time, main thread can get the result     
         System.out.println(future.get());     
     }     
        
 }     
   
   
     class MyCallable implements Callable<String>{   
   
         @Override  
         public String call() throws Exception {   
              return getPageContent();     
         }   
            
         public String getPageContent(){     
             return "Callable method...";     
         }    
     }  
public class FutureTaskSample { 

    public static void main(String[] args) throws InterruptedException, ExecutionException{ 
        //Start a thread to let this thread to do the time exhausting thing 
    Callable call = new MyCallable();
    FutureTask future = new FutureTask(call);
        new Thread(future).start(); 

        //Main thread can do own required thing first 
        //doOwnThing(); 
        System.out.println("Do Own Thing"); 

        //At the needed time, main thread can get the result 
        System.out.println(future.get()); 
    } 


class MyCallable implements Callable<String>{

@Override
public String call() throws Exception {
 return getPageContent(); 
}

public String getPageContent(){ 
        return "Callable method..."; 
    }
} 結果:
Do Own Thing
Callable method...
 
 Example3:
Java代碼
import java.util.concurrent.Callable;   
   
 public class Changgong implements Callable<Integer>{   
   
     private int hours=12;   
     private int amount;   
        
     @Override  
     public Integer call() throws Exception {   
         while(hours>0){   
             System.out.println("I'm working......");   
             amount ++;   
             hours--;   
             Thread.sleep(1000);   
         }   
         return amount;   
     }   
 }  
import java.util.concurrent.Callable;

public class Changgong implements Callable<Integer>{

    private int hours=12;
    private int amount;

    @Override
    public Integer call() throws Exception {
        while(hours>0){
            System.out.println("I'm working......");
            amount ++;
            hours--;
            Thread.sleep(1000);
        }
        return amount;
    }

Java代碼
public class Dizhu {   
            
     public static void main(String args[]){   
         Changgong worker = new Changgong();   
         FutureTask<Integer> jiangong = new FutureTask<Integer>(worker);   
         new Thread(jiangong).start();   
         while(!jiangong.isDone()){   
             try {   
                 System.out.println("看長工做完了沒...");   
                 Thread.sleep(1000);   
             } catch (InterruptedException e) {   
                 // TODO Auto-generated catch block   
                 e.printStackTrace();   
             }   
         }   
         int amount;   
         try {   
             amount = jiangong.get();   
             System.out.println("工作做完了,上交了"+amount);   
         } catch (InterruptedException e) {   
             // TODO Auto-generated catch block   
             e.printStackTrace();   
         } catch (ExecutionException e) {   
             // TODO Auto-generated catch block   
             e.printStackTrace();   
         }   
     }   
 }  
public class Dizhu {

    public static void main(String args[]){
        Changgong worker = new Changgong();
        FutureTask<Integer> jiangong = new FutureTask<Integer>(worker);
        new Thread(jiangong).start();
        while(!jiangong.isDone()){
            try {
                System.out.println("看長工做完了沒...");
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        int amount;
        try {
            amount = jiangong.get();
            System.out.println("工作做完了,上交了"+amount);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ExecutionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

結果:
看工人做完了沒...
I'm working......
看工人做完了沒...
I'm working......
看工人做完了沒...
I'm working......
看工人做完了沒...
I'm working......
看工人做完了沒...
I'm working......
看工人做完了沒...
I'm working......
看工人做完了沒...
I'm working......
看工人做完了沒...
I'm working......
看工人做完了沒...
I'm working......
看工人做完了沒...
I'm working......
看工人做完了沒...
I'm working......
看工人做完了沒...
I'm working......
看工人做完了沒...
工作做完了,上交了12

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章