zoukankan      html  css  js  c++  java
  • Future接口和FutureTask类【FutureTask实现了Runnable和Future接口】

    Future API:

     1     public interface Future<V> {  
     2       
     3         /** 
     4          * Attempts to cancel execution of this task.  This attempt will 
     5          * fail if the task has already completed, has already been cancelled, 
     6          * or could not be cancelled for some other reason. If successful, 
     7          * and this task has not started when <tt>cancel</tt> is called, 
     8          * this task should never run.  If the task has already started, 
     9          * then the <tt>mayInterruptIfRunning</tt> parameter determines 
    10          * whether the thread executing this task should be interrupted in 
    11          * an attempt to stop the task. 
    12          */     
    13         boolean cancel(boolean mayInterruptIfRunning);  
    14       
    15         /** 
    16          * Returns <tt>true</tt> if this task was cancelled before it completed 
    17          * normally. 
    18          * 
    19          * @return <tt>true</tt> if this task was cancelled before it completed 
    20          */  
    21         boolean isCancelled();  
    22       
    23         /** 
    24          * Returns <tt>true</tt> if this task completed. 
    25          * 
    26          * Completion may be due to normal termination, an exception, or 
    27          * cancellation -- in all of these cases, this method will return 
    28          * <tt>true</tt>. 
    29          * 
    30          * @return <tt>true</tt> if this task completed 
    31          */  
    32         boolean isDone();  
    33       
    34         /** 
    35          * Waits if necessary for the computation to complete, and then 
    36          * retrieves its result. 
    37          * 
    38          * @return the computed result 
    39          * @throws CancellationException if the computation was cancelled 
    40          * @throws ExecutionException if the computation threw an 
    41          * exception 
    42          * @throws InterruptedException if the current thread was interrupted 
    43          * while waiting 
    44          */  
    45         V get() throws InterruptedException, ExecutionException;  
    46       
    47         /** 
    48          * Waits if necessary for at most the given time for the computation 
    49          * to complete, and then retrieves its result, if available. 
    50          * 
    51          * @param timeout the maximum time to wait 
    52          * @param unit the time unit of the timeout argument 
    53          * @return the computed result 
    54          * @throws CancellationException if the computation was cancelled 
    55          * @throws ExecutionException if the computation threw an 
    56          * exception 
    57          * @throws InterruptedException if the current thread was interrupted 
    58          * while waiting 
    59          * @throws TimeoutException if the wait timed out 
    60          */  
    61         V get(long timeout, TimeUnit unit)  
    62             throws InterruptedException, ExecutionException, TimeoutException;  
    63     }  

    FutureTask API:

     1     public interface Executor {      
     2         void execute(Runnable command);    
     3     }   
     4       
     5     public interface ExecutorService extends Executor {    
     6         
     7         <T> Future<T> submit(Callable<T> task);         
     8         <T> Future<T> submit(Runnable task, T result);      
     9         Future<?> submit(Runnable task);          
    10         ...       
    11     }    
    12       
    13     public class FutureTask<V>  extends Object    
    14                 implements Future<V>, Runnable {  
    15           FutureTask(Callable<V> callable)     
    16                  //创建一个 FutureTask,一旦运行就执行给定的 Callable。      
    17           FutureTask(Runnable runnable, V result)     
    18                  //创建一个 FutureTask,一旦运行就执行给定的 Runnable,并安排成功完成时 get 返回给定的结果 。    
    19     }  
    20     /*参数:   
    21     runnable - 可运行的任务。   
    22     result - 成功完成时要返回的结果。   
    23     如果不需要特定的结果,则考虑使用下列形式的构造:Future<?> f = new FutureTask<Object>(runnable, null)  */  

    单独使用Runnable时无法获得返回值

    单独使用Callable时

         无法在新线程中(new Thread(Runnable r))使用,只能使用ExecutorService

         Thread类只支持Runnable

    FutureTask

             实现了RunnableFuture,所以兼顾两者优点

             既可以使用ExecutorService,也可以使用Thread

     

    1     Callable pAccount = new PrivateAccount();    
    2         FutureTask futureTask = new FutureTask(pAccount);    
    3         // 使用futureTask创建一个线程    
    4         Thread thread = new Thread(futureTask);    
    5         thread.start();    

     

    =================================================================

    public interface Future<V> Future 表示异步计算的结果。
    Future有个get方法而获取结果只有在计算完成时获取,否则会一直阻塞直到任务转入完成状态,然后会返回结果或者抛出异常。 

      

    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:如有必要,最多等待为使计算完成所给定的时间之后,获取其结果(如果结果可用)。

      6)finishCompletion()该方法在任务完成(包括异常完成、取消)后调用。删除所有正在get获取等待的节点且唤醒节点的线程。和调用done方法和置空callable.

     

    CompletionService接口能拿到按完成顺序拿到一组线程池中所有线程,依靠的就是FutureTask中的finishCompletion()方法。

     

     1     /** 
     2         该方法在任务完成(包括异常完成、取消)后调用。删除所有正在get获取等待的节点且唤醒节点的线程。和调用done方法和置空callable. 
     3         **/  
     4         private void finishCompletion() {  
     5             // assert state > COMPLETING;  
     6             for (WaitNode q; (q = waiters) != null;) {  
     7                 if (UNSAFE.compareAndSwapObject(this, waitersOffset, q, null)) {  
     8                     for (;;) {  
     9                         Thread t = q.thread;  
    10                         if (t != null) {  
    11                             q.thread = null;  
    12                             LockSupport.unpark(t);  
    13                         }  
    14                         WaitNode next = q.next;  
    15                         if (next == null)  
    16                             break;  
    17                         q.next = null; // unlink to help gc  
    18                         q = next;  
    19                     }  
    20                     break;  
    21                 }  
    22             }  
    23       
    24             done();  
    25       
    26             callable = null;        // to reduce footprint  
    27         }  
    1     public class FutureTask<V>  extends Object  
    2         implements Future<V>, Runnable  

      Future是一个接口, FutureTask类是Future 的一个实现类,并实现了Runnable,因此FutureTask可以传递到线程对象Thread中新建一个线程执行。所以可通过Excutor(线程池) 来执行,也可传递给Thread对象执行。如果在主线程中需要执行比较耗时的操作时,但又不想阻塞主线程时,可以把这些作业交给Future对象在后台完成,当主线程将来需要时,就可以通过Future对象获得后台作业的计算结果或者执行状态。 

      FutureTask是为了弥补Thread的不足而设计的,它可以让程序员准确地知道线程什么时候执行完成并获得到线程执行完成后返回的结果(如果有需要)。

     

      FutureTask是一种可以取消的异步的计算任务。它的计算是通过Callable实现的,它等价于可以携带结果的Runnable,并且有三个状态:等待、运行和完成。完成包括所有计算以

    任意的方式结束,包括正常结束、取消和异常。

    Executor框架利用FutureTask来完成异步任务,并可以用来进行任何潜在的耗时的计算。一般FutureTask多用于耗时的计算,主线程可以在完成自己的任务后,再去获取结果。

    FutureTask多用于耗时的计算,主线程可以在完成自己的任务后,再去获取结果

     

     JDK:

      此类提供了对 Future 的基本实现。仅在计算完成时才能检索结果;如果计算尚未完成,则阻塞 get 方法。一旦计算完成,就不能再重新开始或取消计算。

      可使用 FutureTask 包装 Callable 或 Runnable 对象。因为 FutureTask 实现了 Runnable,所以可将 FutureTask 提交给 Executor 执行。

     1     //构造方法摘要  
     2     FutureTask(Callable<V> callable)   
     3               //创建一个 FutureTask,一旦运行就执行给定的 Callable。  
     4       
     5     FutureTask(Runnable runnable, V result)   
     6               //创建一个 FutureTask,一旦运行就执行给定的 Runnable,并安排成功完成时 get 返回给定的结果 。  
     7     //参数:  
     8     runnable - 可运行的任务。  
     9     result - 成功完成时要返回的结果。  
    10     如果不需要特定的结果,则考虑使用下列形式的构造:Future<?> f = new FutureTask<Object>(runnable, null)  

     Example1:

      下面的例子模拟一个会计算账的过程,主线程已经获得其他帐户的总额了,为了不让主线程等待 PrivateAccount类的计算结果的返回而启用新的线程去处理, 并使用 FutureTask对象来监控,这样,主线程还可以继续做其他事情, 最后需要计算总额的时候再尝试去获得privateAccount 的信息。 

     1     package test;  
     2       
     3     import java.util.Random;  
     4     import java.util.concurrent.Callable;  
     5     import java.util.concurrent.ExecutionException;  
     6     import java.util.concurrent.FutureTask;  
     7       
     8     /** 
     9      * 
    10      * @author Administrator 
    11      * 
    12      */  
    13     @SuppressWarnings("all")  
    14     public class FutureTaskDemo {  
    15         public static void main(String[] args) {  
    16             // 初始化一个Callable对象和FutureTask对象  
    17             Callable pAccount = new PrivateAccount();  
    18             FutureTask futureTask = new FutureTask(pAccount);  
    19             // 使用futureTask创建一个线程  
    20             Thread pAccountThread = new Thread(futureTask);  
    21             System.out.println("futureTask线程现在开始启动,启动时间为:" + System.nanoTime());  
    22             pAccountThread.start();  
    23             System.out.println("主线程开始执行其他任务");  
    24             // 从其他账户获取总金额  
    25             int totalMoney = new Random().nextInt(100000);  
    26             System.out.println("现在你在其他账户中的总金额为" + totalMoney);  
    27             System.out.println("等待私有账户总金额统计完毕...");  
    28             // 测试后台的计算线程是否完成,如果未完成则等待  
    29             while (!futureTask.isDone()) {  
    30                 try {  
    31                     Thread.sleep(500);  
    32                     System.out.println("私有账户计算未完成继续等待...");  
    33                 } catch (InterruptedException e) {  
    34                     e.printStackTrace();  
    35                 }  
    36             }  
    37             System.out.println("futureTask线程计算完毕,此时时间为" + System.nanoTime());  
    38             Integer privateAccountMoney = null;  
    39             try {  
    40                 privateAccountMoney = (Integer) futureTask.get();  
    41             } catch (InterruptedException e) {  
    42                 e.printStackTrace();  
    43             } catch (ExecutionException e) {  
    44                 e.printStackTrace();  
    45             }  
    46             System.out.println("您现在的总金额为:" + totalMoney + privateAccountMoney.intValue());  
    47         }  
    48     }  
    49       
    50     @SuppressWarnings("all")  
    51     class PrivateAccount implements Callable {  
    52         Integer totalMoney;  
    53       
    54         @Override  
    55         public Object call() throws Exception {  
    56             Thread.sleep(5000);  
    57             totalMoney = new Integer(new Random().nextInt(10000));  
    58             System.out.println("您当前有" + totalMoney + "在您的私有账户中");  
    59             return totalMoney;  
    60         }  
    61       
    62     }  

     运行结果

       

     Example2:

     1     public class FutureTaskSample {  
     2           
     3         static FutureTask<String> future = new FutureTask(new Callable<String>(){  
     4             public String call(){  
     5                 return getPageContent();  
     6             }  
     7         });  
     8           
     9         public static void main(String[] args) throws InterruptedException, ExecutionException{  
    10             //Start a thread to let this thread to do the time exhausting thing  
    11             new Thread(future).start();  
    12       
    13             //Main thread can do own required thing first  
    14             doOwnThing();  
    15       
    16             //At the needed time, main thread can get the result  
    17             System.out.println(future.get());  
    18         }  
    19           
    20         public static String doOwnThing(){  
    21             return "Do Own Thing";  
    22         }  
    23         public static String getPageContent(){  
    24             return "Callable method...";  
    25         }  
    26     }  

    结果为:Callable method...
    不科学啊,为毛??!

    改为这样,结果就正常:
     1     public class FutureTaskSample {    
     2             
     3         public static void main(String[] args) throws InterruptedException, ExecutionException{    
     4             //Start a thread to let this thread to do the time exhausting thing    
     5             Callable call = new MyCallable();  
     6             FutureTask future = new FutureTask(call);  
     7             new Thread(future).start();    
     8         
     9             //Main thread can do own required thing first    
    10             //doOwnThing();    
    11             System.out.println("Do Own Thing");    
    12               
    13             //At the needed time, main thread can get the result    
    14             System.out.println(future.get());    
    15         }    
    16           
    17     }    
    18       
    19       
    20         class MyCallable implements Callable<String>{  
    21       
    22             @Override  
    23             public String call() throws Exception {  
    24                  return getPageContent();    
    25             }  
    26               
    27             public String getPageContent(){    
    28                 return "Callable method...";    
    29             }   
    30         }  

    结果:

    Do Own Thing
    Callable method...

     Example3:

     1     import java.util.concurrent.Callable;  
     2       
     3     public class Changgong implements Callable<Integer>{  
     4       
     5         private int hours=12;  
     6         private int amount;  
     7           
     8         @Override  
     9         public Integer call() throws Exception {  
    10             while(hours>0){  
    11                 System.out.println("I'm working......");  
    12                 amount ++;  
    13                 hours--;  
    14                 Thread.sleep(1000);  
    15             }  
    16             return amount;  
    17         }  
    18     }  
     1     public class Dizhu {  
     2               
     3         public static void main(String args[]){  
     4             Changgong worker = new Changgong();  
     5             FutureTask<Integer> jiangong = new FutureTask<Integer>(worker);  
     6             new Thread(jiangong).start();  
     7             while(!jiangong.isDone()){  
     8                 try {  
     9                     System.out.println("看长工做完了没...");  
    10                     Thread.sleep(1000);  
    11                 } catch (InterruptedException e) {  
    12                     // TODO Auto-generated catch block  
    13                     e.printStackTrace();  
    14                 }  
    15             }  
    16             int amount;  
    17             try {  
    18                 amount = jiangong.get();  
    19                 System.out.println("工作做完了,上交了"+amount);  
    20             } catch (InterruptedException e) {  
    21                 // TODO Auto-generated catch block  
    22                 e.printStackTrace();  
    23             } catch (ExecutionException e) {  
    24                 // TODO Auto-generated catch block  
    25                 e.printStackTrace();  
    26             }  
    27         }  
    28     }  
    结果:
    看工人做完了没...
    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
      1     /** 
      2      * Factory and utility methods for {@link Executor}, {@link 
      3      * ExecutorService}, {@link ScheduledExecutorService}, {@link 
      4      * ThreadFactory}, and {@link Callable} classes defined in this 
      5      * package. This class supports the following kinds of methods: 
      6      * 
      7      * <ul> 
      8      *   <li> Methods that create and return an {@link ExecutorService} 
      9      *        set up with commonly useful configuration settings. 
     10      *   <li> Methods that create and return a {@link ScheduledExecutorService} 
     11      *        set up with commonly useful configuration settings. 
     12      *   <li> Methods that create and return a "wrapped" ExecutorService, that 
     13      *        disables reconfiguration by making implementation-specific methods 
     14      *        inaccessible. 
     15      *   <li> Methods that create and return a {@link ThreadFactory} 
     16      *        that sets newly created threads to a known state. 
     17      *   <li> Methods that create and return a {@link Callable} 
     18      *        out of other closure-like forms, so they can be used 
     19      *        in execution methods requiring <tt>Callable</tt>. 
     20      * </ul> 
     21      * 
     22      * @since 1.5 
     23      * @author Doug Lea 
     24      */  
     25     public class Executors {  
     26       
     27         /** 
     28          * Creates a thread pool that reuses a fixed number of threads 
     29          * operating off a shared unbounded queue.  At any point, at most 
     30          * <tt>nThreads</tt> threads will be active processing tasks. 
     31          * If additional tasks are submitted when all threads are active, 
     32          * they will wait in the queue until a thread is available. 
     33          * If any thread terminates due to a failure during execution 
     34          * prior to shutdown, a new one will take its place if needed to 
     35          * execute subsequent tasks.  The threads in the pool will exist 
     36          * until it is explicitly {@link ExecutorService#shutdown shutdown}. 
     37          * 
     38          * @param nThreads the number of threads in the pool 
     39          * @return the newly created thread pool 
     40          * @throws IllegalArgumentException if <tt>nThreads &lt;= 0</tt> 
     41          */  
     42         public static ExecutorService newFixedThreadPool(int nThreads) {  
     43             return new ThreadPoolExecutor(nThreads, nThreads,  
     44                                           0L, TimeUnit.MILLISECONDS,  
     45                                           new LinkedBlockingQueue<Runnable>());  
     46         }  
     47       
     48         /** 
     49          * Creates a thread pool that reuses a fixed number of threads 
     50          * operating off a shared unbounded queue, using the provided 
     51          * ThreadFactory to create new threads when needed.  At any point, 
     52          * at most <tt>nThreads</tt> threads will be active processing 
     53          * tasks.  If additional tasks are submitted when all threads are 
     54          * active, they will wait in the queue until a thread is 
     55          * available.  If any thread terminates due to a failure during 
     56          * execution prior to shutdown, a new one will take its place if 
     57          * needed to execute subsequent tasks.  The threads in the pool will 
     58          * exist until it is explicitly {@link ExecutorService#shutdown 
     59          * shutdown}. 
     60          * 
     61          * @param nThreads the number of threads in the pool 
     62          * @param threadFactory the factory to use when creating new threads 
     63          * @return the newly created thread pool 
     64          * @throws NullPointerException if threadFactory is null 
     65          * @throws IllegalArgumentException if <tt>nThreads &lt;= 0</tt> 
     66          */  
     67         public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) {  
     68             return new ThreadPoolExecutor(nThreads, nThreads,  
     69                                           0L, TimeUnit.MILLISECONDS,  
     70                                           new LinkedBlockingQueue<Runnable>(),  
     71                                           threadFactory);  
     72         }  
     73       
     74         /** 
     75          * Creates an Executor that uses a single worker thread operating 
     76          * off an unbounded queue. (Note however that if this single 
     77          * thread terminates due to a failure during execution prior to 
     78          * shutdown, a new one will take its place if needed to execute 
     79          * subsequent tasks.)  Tasks are guaranteed to execute 
     80          * sequentially, and no more than one task will be active at any 
     81          * given time. Unlike the otherwise equivalent 
     82          * <tt>newFixedThreadPool(1)</tt> the returned executor is 
     83          * guaranteed not to be reconfigurable to use additional threads. 
     84          * 
     85          * @return the newly created single-threaded Executor 
     86          */  
     87         public static ExecutorService newSingleThreadExecutor() {  
     88             return new FinalizableDelegatedExecutorService  
     89                 (new ThreadPoolExecutor(1, 1,  
     90                                         0L, TimeUnit.MILLISECONDS,  
     91                                         new LinkedBlockingQueue<Runnable>()));  
     92         }  
     93       
     94         /** 
     95          * Creates an Executor that uses a single worker thread operating 
     96          * off an unbounded queue, and uses the provided ThreadFactory to 
     97          * create a new thread when needed. Unlike the otherwise 
     98          * equivalent <tt>newFixedThreadPool(1, threadFactory)</tt> the 
     99          * returned executor is guaranteed not to be reconfigurable to use 
    100          * additional threads. 
    101          * 
    102          * @param threadFactory the factory to use when creating new 
    103          * threads 
    104          * 
    105          * @return the newly created single-threaded Executor 
    106          * @throws NullPointerException if threadFactory is null 
    107          */  
    108         public static ExecutorService newSingleThreadExecutor(ThreadFactory threadFactory) {  
    109             return new FinalizableDelegatedExecutorService  
    110                 (new ThreadPoolExecutor(1, 1,  
    111                                         0L, TimeUnit.MILLISECONDS,  
    112                                         new LinkedBlockingQueue<Runnable>(),  
    113                                         threadFactory));  
    114         }  
    115       
    116         /** 
    117          * Creates a thread pool that creates new threads as needed, but 
    118          * will reuse previously constructed threads when they are 
    119          * available.  These pools will typically improve the performance 
    120          * of programs that execute many short-lived asynchronous tasks. 
    121          * Calls to <tt>execute</tt> will reuse previously constructed 
    122          * threads if available. If no existing thread is available, a new 
    123          * thread will be created and added to the pool. Threads that have 
    124          * not been used for sixty seconds are terminated and removed from 
    125          * the cache. Thus, a pool that remains idle for long enough will 
    126          * not consume any resources. Note that pools with similar 
    127          * properties but different details (for example, timeout parameters) 
    128          * may be created using {@link ThreadPoolExecutor} constructors. 
    129          * 
    130          * @return the newly created thread pool 
    131          */  
    132         public static ExecutorService newCachedThreadPool() {  
    133             return new ThreadPoolExecutor(0, Integer.MAX_VALUE,  
    134                                           60L, TimeUnit.SECONDS,  
    135                                           new SynchronousQueue<Runnable>());  
    136         }  
    137       
    138         /** 
    139          * Creates a thread pool that creates new threads as needed, but 
    140          * will reuse previously constructed threads when they are 
    141          * available, and uses the provided 
    142          * ThreadFactory to create new threads when needed. 
    143          * @param threadFactory the factory to use when creating new threads 
    144          * @return the newly created thread pool 
    145          * @throws NullPointerException if threadFactory is null 
    146          */  
    147         public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) {  
    148             return new ThreadPoolExecutor(0, Integer.MAX_VALUE,  
    149                                           60L, TimeUnit.SECONDS,  
    150                                           new SynchronousQueue<Runnable>(),  
    151                                           threadFactory);  
    152         }  
    153       
    154         /** 
    155          * Creates a single-threaded executor that can schedule commands 
    156          * to run after a given delay, or to execute periodically. 
    157          * (Note however that if this single 
    158          * thread terminates due to a failure during execution prior to 
    159          * shutdown, a new one will take its place if needed to execute 
    160          * subsequent tasks.)  Tasks are guaranteed to execute 
    161          * sequentially, and no more than one task will be active at any 
    162          * given time. Unlike the otherwise equivalent 
    163          * <tt>newScheduledThreadPool(1)</tt> the returned executor is 
    164          * guaranteed not to be reconfigurable to use additional threads. 
    165          * @return the newly created scheduled executor 
    166          */  
    167         public static ScheduledExecutorService newSingleThreadScheduledExecutor() {  
    168             return new DelegatedScheduledExecutorService  
    169                 (new ScheduledThreadPoolExecutor(1));  
    170         }  
    171       
    172         /** 
    173          * Creates a single-threaded executor that can schedule commands 
    174          * to run after a given delay, or to execute periodically.  (Note 
    175          * however that if this single thread terminates due to a failure 
    176          * during execution prior to shutdown, a new one will take its 
    177          * place if needed to execute subsequent tasks.)  Tasks are 
    178          * guaranteed to execute sequentially, and no more than one task 
    179          * will be active at any given time. Unlike the otherwise 
    180          * equivalent <tt>newScheduledThreadPool(1, threadFactory)</tt> 
    181          * the returned executor is guaranteed not to be reconfigurable to 
    182          * use additional threads. 
    183          * @param threadFactory the factory to use when creating new 
    184          * threads 
    185          * @return a newly created scheduled executor 
    186          * @throws NullPointerException if threadFactory is null 
    187          */  
    188         public static ScheduledExecutorService newSingleThreadScheduledExecutor(ThreadFactory threadFactory) {  
    189             return new DelegatedScheduledExecutorService  
    190                 (new ScheduledThreadPoolExecutor(1, threadFactory));  
    191         }  
    192       
    193         /** 
    194          * Creates a thread pool that can schedule commands to run after a 
    195          * given delay, or to execute periodically. 
    196          * @param corePoolSize the number of threads to keep in the pool, 
    197          * even if they are idle. 
    198          * @return a newly created scheduled thread pool 
    199          * @throws IllegalArgumentException if <tt>corePoolSize &lt; 0</tt> 
    200          */  
    201         public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {  
    202             return new ScheduledThreadPoolExecutor(corePoolSize);  
    203         }  
    204       
    205         /** 
    206          * Creates a thread pool that can schedule commands to run after a 
    207          * given delay, or to execute periodically. 
    208          * @param corePoolSize the number of threads to keep in the pool, 
    209          * even if they are idle. 
    210          * @param threadFactory the factory to use when the executor 
    211          * creates a new thread. 
    212          * @return a newly created scheduled thread pool 
    213          * @throws IllegalArgumentException if <tt>corePoolSize &lt; 0</tt> 
    214          * @throws NullPointerException if threadFactory is null 
    215          */  
    216         public static ScheduledExecutorService newScheduledThreadPool(  
    217                 int corePoolSize, ThreadFactory threadFactory) {  
    218             return new ScheduledThreadPoolExecutor(corePoolSize, threadFactory);  
    219         }  
    220         ........  
    221       
    222         /** Cannot instantiate. */  
    223         private Executors() {}  
    224     }  

     ================================================================================

    FutureTask实现原理-源码

        下面我们介绍一下FutureTask内部的一些实现机制。下文从以下几点叙述:

    1. 类继承结构
    2. 核心成员变量
    3. 内部状态转换
    4. 核心方法解析

    1 类继承结构

          首先我们看一下FutureTask的继承结构:   

     

          FutureTask实现了RunnableFuture接口,而RunnableFuture继承了Runnable和Future,也就是说FutureTask既是Runnable,也是Future。

    2 核心成员变量

        FutureTask内部定义了以下变量,以及它们的含义如下

    • volatile int state:表示对象状态,volatile关键字保证了内存可见性。futureTask中定义了7种状态,代表了7种不同的执行状态
    1 private static final int NEW          = 0; //任务新建和执行中
    2 private static final int COMPLETING   = 1; //任务将要执行完毕
    3 private static final int NORMAL       = 2; //任务正常执行结束
    4 private static final int EXCEPTIONAL  = 3; //任务异常
    5 private static final int CANCELLED    = 4; //任务取消
    6 private static final int INTERRUPTING = 5; //任务线程即将被中断
    7 private static final int INTERRUPTED  = 6; //任务线程已中断
    • Callable<V> callable:被提交的任务
    • Object outcome:任务执行结果或者任务异常
    • volatile Thread runner:执行任务的线程
    • volatile WaitNode waiters:等待节点,关联等待线程
    • long stateOffset:state字段的内存偏移量
    • long runnerOffset:runner字段的内存偏移量
    • long waitersOffset:waiters字段的内存偏移量

        后三个字段是配合Unsafe类做CAS操作使用的。

    3 内部状态转换

        FutureTask中使用state表示任务状态,state值变更的由CAS操作保证原子性。

        FutureTask对象初始化时,在构造器中把state置为为NEW,之后状态的变更依据具体执行情况来定。

       例如任务执行正常结束前,state会被设置成COMPLETING,代表任务即将完成,接下来很快就会被设置为NARMAL或者EXCEPTIONAL,这取决于调用Runnable中的call()方法是否抛出了异常。有异常则后者,反之前者。

      任务提交后、任务结束前取消任务,那么有可能变为CANCELLED或者INTERRUPTED。在调用cancel方法时,如果传入false表示不中断线程,state会被置为CANCELLED,反之state先被变为INTERRUPTING,后变为INTERRUPTED。

         总结下,FutureTask的状态流转过程,可以出现以下四种情况:

            1. 任务正常执行并返回。 NEW -> COMPLETING -> NORMAL

        2. 执行中出现异常。NEW -> COMPLETING -> EXCEPTIONAL

            3. 任务执行过程中被取消,并且不响应中断。NEW -> CANCELLED

        4. 任务执行过程中被取消,并且响应中断。 NEW -> INTERRUPTING -> INTERRUPTED  

    4 核心方法解析

    接下来我们一起扒一扒FutureTask的源码。我们先看一下任务线程是怎么执行的。当任务被提交到线程池后,会执行futureTask的run()方法。

    1 public void run()

     1 public void run() {<br>        // 校验任务状态
     2         if (state != NEW || !UNSAFE.compareAndSwapObject(this, runnerOffset, null, Thread.currentThread()))
     3             return;
     4         try {
     5             Callable<V> c = callable;<br>       // double check
     6             if (c != null && state == NEW) {
     7                 V result;
     8                 boolean ran;
     9                 try {<br>            //执行业务代码
    10                     result = c.call();
    11                     ran = true;
    12                 } catch (Throwable ex) {
    13                     result = null;
    14                     ran = false;
    15                     setException(ex);
    16                 }
    17                 if (ran)
    18                     set(result);
    19             }
    20         } finally {<br>        // 重置runner
    21             runner = null;
    22             int s = state;
    23             if (s >= INTERRUPTING)
    24                 handlePossibleCancellationInterrupt(s);
    25         }
    26     }

    翻译一下,这个方法经历了以下几步

    1. 校验当前任务状态是否为NEW以及runner是否已赋值。这一步是防止任务被取消。
    2. double-check任务状态state
    3. 执行业务逻辑,也就是c.call()方法被执行
    4. 如果业务逻辑异常,则调用setException方法将异常对象赋给outcome,并且更新state值
    5. 如果业务正常,则调用set方法将执行结果赋给outcome,并且更新state值

     我们继续往下看,setException(Throwable t)和set(V v) 具体是怎么做的

     1 protected void set(V v) {
     2         // state状态 NEW->COMPLETING
     3         if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
     4             outcome = v;
     5             // COMPLETING -> NORMAL 到达稳定状态
     6             UNSAFE.putOrderedInt(this, stateOffset, NORMAL);
     7             // 一些结束工作
     8             finishCompletion();
     9         }
    10     }
     1 protected void setException(Throwable t) {
     2     // state状态 NEW->COMPLETING
     3     if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
     4         outcome = t;
     5         // COMPLETING -> EXCEPTIONAL 到达稳定状态
     6         UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL);
     7         // 一些结束工作
     8         finishCompletion();
     9     }
    10 } 

    code中的注释已经写的很清楚,故不翻译了。状态变更的原子性由unsafe对象提供的CAS操作保证。FutureTask的outcome变量存储执行结果或者异常对象,会由主线程返回。

    2  get()和get(long timeout, TimeUnit unit)

        任务由线程池提供的线程执行,那么这时候主线程则会阻塞,直到任务线程唤醒它们。我们通过get(long timeout, TimeUnit unit)方法看看是怎么做的  

     1 public V get(long timeout, TimeUnit unit)
     2         throws InterruptedException, ExecutionException, TimeoutException {
     3         if (unit == null)
     4             throw new NullPointerException();
     5         int s = state;
     6         if (s <= COMPLETING &&
     7             (s = awaitDone(true, unit.toNanos(timeout))) <= COMPLETING)
     8             throw new TimeoutException();
     9         return report(s);
    10     }

    get的源码很简洁,首先校验参数,然后根据state状态判断是否超时,如果超时则异常,不超时则调用report(s)去获取最终结果。

    当 s<= COMPLETING时,表明任务仍然在执行且没有被取消。如果它为true,那么走到awaitDone方法。

    awaitDone是futureTask实现阻塞的关键方法,我们重点关注一下它的实现原理。

     1 /**
     2  * 等待任务执行完毕,如果任务取消或者超时则停止
     3  * @param timed 为true表示设置超时时间
     4  * @param nanos 超时时间
     5  * @return 任务完成时的状态
     6  * @throws InterruptedException
     7  */
     8 private int awaitDone(boolean timed, long nanos)
     9         throws InterruptedException {
    10     // 任务截止时间
    11     final long deadline = timed ? System.nanoTime() + nanos : 0L;
    12     WaitNode q = null;
    13     boolean queued = false;
    14     // 自旋
    15     for (;;) {
    16         if (Thread.interrupted()) {
    17             //线程中断则移除等待线程,并抛出异常
    18             removeWaiter(q);
    19             throw new InterruptedException();
    20         }
    21         int s = state;
    22         if (s > COMPLETING) {
    23             // 任务可能已经完成或者被取消了
    24             if (q != null)
    25                 q.thread = null;
    26             return s;
    27         }
    28         else if (s == COMPLETING)
    29             // 可能任务线程被阻塞了,主线程让出CPU
    30             Thread.yield();
    31         else if (q == null)
    32             // 等待线程节点为空,则初始化新节点并关联当前线程
    33             q = new WaitNode();
    34         else if (!queued)
    35             // 等待线程入队列,成功则queued=true
    36             queued = UNSAFE.compareAndSwapObject(this, waitersOffset,
    37                     q.next = waiters, q);
    38         else if (timed) {
    39             nanos = deadline - System.nanoTime();
    40             if (nanos <= 0L) {
    41                 //已经超时的话,移除等待节点
    42                 removeWaiter(q);
    43                 return state;
    44             }
    45             // 未超时,将当前线程挂起指定时间
    46             LockSupport.parkNanos(this, nanos);
    47         }
    48         else
    49             // timed=false时会走到这里,挂起当前线程
    50             LockSupport.park(this);
    51     }
    52 }

    注释里也很清楚的写明了每一步的作用,我们以设置超时时间为例,总结一下过程

    1. 计算deadline,也就是到某个时间点后如果还没有返回结果,那么就超时了。
    2. 进入自旋,也就是死循环。
    3. 首先判断是否响应线程中断。对于线程中断的响应往往会放在线程进入阻塞之前,这里也印证了这一点。
    4. 判断state值,如果>COMPLETING表明任务已经取消或者已经执行完毕,就可以直接返回了。
    5. 如果任务还在执行,则为当前线程初始化一个等待节点WaitNode,入等待队列。这里和AQS的等待队列类似,只不过Node只关联线程,而没有状态。AQS里面的等待节点是有状态的。
    6. 计算nanos,判断是否已经超时。如果已经超时,则移除所有等待节点,直接返回state。超时的话,state的值仍然还是COMPLETING。
    7. 如果还未超时,就通过LockSupprot类提供的方法在指定时间内挂起当前线程,等待任务线程唤醒或者超时唤醒。

    当线程被挂起之后,如果任务线程执行完毕,就会唤醒等待线程哦。这一步就是在finishCompletion里面做的,前面已经提到这个方法。我们再看看这个方法具体做了哪些事吧~

     1 /**
     2  * 移除并唤醒所有等待线程,执行done,置空callable
     3  * nulls out callable.
     4  */
     5 private void finishCompletion() {
     6     //遍历等待节点
     7     for (WaitNode q; (q = waiters) != null;) {
     8         if (UNSAFE.compareAndSwapObject(this, waitersOffset, q, null)) {
     9             for (;;) {
    10                 Thread t = q.thread;
    11                 if (t != null) {
    12                     q.thread = null;
    13                     //唤醒等待线程
    14                     LockSupport.unpark(t);
    15                 }
    16                 WaitNode next = q.next;
    17                 if (next == null)
    18                     break;
    19                 // unlink to help gc
    20                 q.next = null;
    21                 q = next;
    22             }
    23             break;
    24         }
    25     }
    26     //模板方法,可以被覆盖
    27     done();
    28     //清空callable
    29     callable = null;
    30 }

    由代码和注释可以看出来,这个方法的作用主要在于唤醒等待线程。由前文可知,当任务正常结束或者异常时,都会调用finishCompletion去唤醒等待线程。这个时候,等待线程就可以醒来,开开心心的获得结果啦。  

    最后我们看一下任务取消  

    3 public boolean cancel(boolean mayInterruptIfRunning)

      注意,取消操作不一定会起作用,这里我们先贴个demo

    1 public class FutureDemo {
     2     public static void main(String[] args) {
     3         ThreadPoolExecutor executorService = (ThreadPoolExecutor) Executors.newFixedThreadPool(1);
     4         // 预创建线程
     5         executorService.prestartCoreThread();
     6 
     7         Future future = executorService.submit(new Callable<Object>() {
     8             @Override
     9             public Object call() {
    10                 System.out.println("start to run callable");
    11                 Long start = System.currentTimeMillis();
    12                 while (true) {
    13                     Long current = System.currentTimeMillis();
    14                     if ((current - start) > 1000) {
    15                         System.out.println("当前任务执行已经超过1s");
    16                         return 1;
    17                     }
    18                 }
    19             }
    20         });
    21 
    22         System.out.println(future.cancel(false));
    23 
    24         try {
    25             Thread.currentThread().sleep(3000);
    26             executorService.shutdown();
    27         } catch (Exception e) {
    28             //NO OP
    29         }
    30     }
    31 }

    我们多次测试后发现,出现了2种打印结果,如图

                              结果1

                              结果2    

    第一种是任务压根没取消,第二种则是任务压根没提交成功。 

        方法签名注释告诉我们,取消操作是可能会失败的,如果当前任务已经结束或者已经取消,则当前取消操作会失败。如果任务尚未开始,那么任务不会被执行。这就解释了出现上图结果2的情况。我们还是从源码去分析cancel()究竟做了哪些事。

     

     1 public boolean cancel(boolean mayInterruptIfRunning) {
     2         if (state != NEW)
     3             return false;
     4         if (mayInterruptIfRunning) {
     5             if (!UNSAFE.compareAndSwapInt(this, stateOffset, NEW, INTERRUPTING))
     6                 return false;
     7             Thread t = runner;
     8             if (t != null)
     9                 t.interrupt();
    10             UNSAFE.putOrderedInt(this, stateOffset, INTERRUPTED); // final state
    11         }
    12         else if (!UNSAFE.compareAndSwapInt(this, stateOffset, NEW, CANCELLED))
    13             return false;
    14         finishCompletion();
    15         return true;
    16     }

     

    执行逻辑如下

    1. state不为NEW时,任务即将进入终态,直接返回false表明取消操作失败。
    2. state状态为NEW,任务可能已经开始执行,也可能还未开始。
    3. mayInterruptIfRunning表明是否中断线程。若是,则尝试将state设置为INTERRUPTING,并且中断线程,之后将state设置为终态INTERRUPTED。
    4. 如果mayInterruptIfRunning=false,则不中断线程,把state设置为CANCELLED
    5. 移除等待线程并唤醒。
    6. 返回true

        可见,cancel()方法改变了futureTask的状态位,如果传入的是false并且业务逻辑已经开始执行,当前任务是不会被终止的,而是会继续执行,直到异常或者执行完毕。如果传入的是true,会调用当前线程的interrupt()方法,把中断标志位设为true。

        事实上,除非线程自己停止自己的任务,或者退出JVM,是没有其他方法完全终止一个线程的任务的。mayInterruptIfRunning=true,通过希望当前线程可以响应中断的方式来结束任务。当任务被取消后,会被封装为CancellationException抛出。

    总结

      总结一下,futureTask中的任务状态由变量state表示,任务状态都基于state判断。而futureTask的阻塞则是通过自旋+挂起线程实现。理解FutureTask的内部实现机制,我们使用Future时才能更加得心应手。文中掺杂着笔者的个人理解,如果有不正之处,还望读者多多指正

  • 相关阅读:
    学习python -- 第018天 os模块
    学习python -- 第017天 文件读写
    重看算法 -- 动态规划 最大子段和问题
    重看算法 -- 递归与分治
    学习python -- 第016天 模块
    学习python -- 第016天 浅拷贝和深拷贝
    网络字节序、主机字节序(摘抄)
    C++/C常量
    结构化程序设计
    循环(高质量4.10)
  • 原文地址:https://www.cnblogs.com/bsjl/p/8649362.html
Copyright © 2011-2022 走看看