Future和FutureTask


上次介紹了Callable實現多線程的方法。現在介紹和Callable搭配的類。上一篇只是簡單的用Callable做了一個demo。

一、Future

1.關於callable和runable的區別(上次已經介紹)

  • Callable可以在任務結束的時候提供一個返回值Future對象,Runnable無法提供這個功能

  • Callable的call方法分可以拋出異常,而Runnable的run方法不能拋出異常。

  • Callable規定的方法是call(),而Runnable規定的方法是run().

2.Future介紹

Future就是對於具體的Runnable或者Callable任務的執行結果進行取消、查詢是否完成、獲取結果。必要時可以通過get方法獲取執行結果,該方法會阻塞直到任務返回結果。

Future類位於java.util.concurrent包下,它是一個接口:

public  interface  Future<V> {
     boolean  cancel( boolean  mayInterruptIfRunning);
     boolean  isCancelled();
     boolean  isDone();
     V get()  throws  InterruptedException, ExecutionException;
     V get( long  timeout, TimeUnit unit)
         throws  InterruptedException, ExecutionException, TimeoutException;
}

在Future接口中聲明了5個方法,下面依次解釋每個方法的作用:

  • cancel方法用來取消任務,如果取消任務成功則返回true,如果取消任務失敗則返回false。參數mayInterruptIfRunning表示是否允許取消正在執行卻沒有執行完畢的任務,如果設置true,則表示可以取消正在執行過程中的任務。如果任務已經完成,則無論mayInterruptIfRunning為true還是false,此方法肯定返回false,即如果取消已經完成的任務會返回false;如果任務正在執行,若mayInterruptIfRunning設置為true,則返回true,若mayInterruptIfRunning設置為false,則返回false;如果任務還沒有執行,則無論mayInterruptIfRunning為true還是false,肯定返回true。
  • isCancelled方法表示任務是否被取消成功,如果在任務正常完成前被取消成功,則返回 true。
  • isDone方法表示任務是否已經完成,若任務完成,則返回true;
  • get()方法用來獲取執行結果,這個方法會產生阻塞,會一直等到任務執行完畢才返回;
  • get(long timeout, TimeUnit unit)用來獲取執行結果,如果在指定時間內,還沒獲取到結果,就直接返回null。

  也就是說Future提供了三種功能:

  1)判斷任務是否完成;

  2)能夠中斷任務;

  3)能夠獲取任務執行結果。

  因為Future只是一個接口,所以是無法直接用來創建對象使用的,因此就有了FutureTask。

3.測試

public  class  TestCallable {
     public  static  void  main(String[] args) {
         ExecutorService executor = Executors.newCachedThreadPool();
         Task task =  new  Task();
         Future<Integer> result = executor.submit(task);
         executor.shutdown();
 
         try  {
             Thread.sleep( 1000 );
         catch  (InterruptedException e1) {
             e1.printStackTrace();
         }
 
         System.out.println( "主線程在執行任務" );
 
         try  {
             System.out.println( "task運行結果" +result.get());
         catch  (InterruptedException | ExecutionException e) {
             e.printStackTrace();
         }
 
         System.out.println( "所有任務執行完畢" );
     }
}
class  Task  implements  Callable<Integer>{
     @Override
     public  Integer call()  throws  Exception {
         System.out.println( "子線程在進行計算" );
         Thread.sleep( 3000 );
         int  sum =  0 ;
         for ( int  i= 0 ;i< 100 ;i++){
             sum += i;
         }
         return  sum;
     }
}

結果:

子線程在進行計算
主線程在執行任務
task運行結果4950
所有任務執行完畢

二、FutureTask

1.FutureTask的實現

public class FutureTask<V> implements RunnableFuture<V>

FutureTask類實現了RunnableFuture接口,我們看一下RunnableFuture接口的實現:

public interface RunnableFuture<V> extends Runnable, Future<V> {  void run();  }

可以看出RunnableFuture繼承了Runnable接口和Future接口,而FutureTask實現了RunnableFuture接口。

也就是說:

FutureTask實現了Runnable,因此它既可以通過Thread包裝來直接執行,也可以提交給ExecuteService來執行。 
FutureTask實現了Futrue可以直接通過get()函數獲取執行結果,該函數會阻塞,直到結果返回。

FutureTask提供了2個構造器:

public FutureTask(Callable<V> callable) {}
public FutureTask(Runnable runnable, V result) {}

FutureTask是Future接口的一個實現類(唯一的實現類)。

 

2.測試

public  class  FutureTaskTest {
     public  static  void  main(String[] args) {
         ExecutorService executor = Executors.newCachedThreadPool();
         newTask task =  new  newTask();
         FutureTask<Integer> futureTask =  new  FutureTask<Integer>(task);
         executor.submit(futureTask);
         executor.shutdown();
         try  {
             Thread.sleep( 1000 );
         catch  (InterruptedException e1) {
             e1.printStackTrace();
         }
 
         System.out.println( "主線程在執行任務" );
 
         try  {
             System.out.println( "task運行結果"  + futureTask.get());
         catch  (InterruptedException | ExecutionException e) {
             e.printStackTrace();
         }
 
         System.out.println( "所有任務執行完畢" );
     }
}
 
class  newTask  implements  Callable<Integer> {
     @Override
     public  Integer call()  throws  Exception {
         System.out.println( "子線程在進行計算" );
         Thread.sleep( 3000 );
         int  sum =  0 ;
         for  ( int  i =  0 ; i <  100 ; i++){
             sum += i;
         }
         return  sum;
     }
 
}

結果:

子線程在進行計算
主線程在執行任務
task運行結果4950
所有任務執行完畢


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM