最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Future與FutureTask接口實現(xiàn)示例詳解

 更新時間:2022年10月13日 14:05:10   作者:mike_cheng  
這篇文章主要為大家介紹了Future與FutureTask接口實現(xiàn)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪

正文

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

Future類

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

/** 
* @see FutureTask 
 * @see Executor 
 * @since 1.5 
 * @author Doug Lea 
 * @param <V> The result type returned by this Future's <tt>get</tt> method 
 */  
public interface Future<V> {  
    /** 
     * Attempts to cancel execution of this task.  This attempt will 
     * fail if the task has already completed, has already been cancelled, 
     * or could not be cancelled for some other reason. If successful, 
     * and this task has not started when <tt>cancel</tt> is called, 
     * this task should never run.  If the task has already started, 
     * then the <tt>mayInterruptIfRunning</tt> parameter determines 
     * whether the thread executing this task should be interrupted in 
     * an attempt to stop the task.     * 
     */  
    boolean cancel(boolean mayInterruptIfRunning);  
    /** 
     * Returns <tt>true</tt> if this task was cancelled before it completed 
     * normally. 
     */  
    boolean isCancelled();  
    /** 
     * Returns <tt>true</tt> if this task completed. 
     * 
     */  
    boolean isDone();  
    /** 
     * Waits if necessary for the computation to complete, and then 
     * retrieves its result. 
     * 
     * @return the computed result 
     */  
    V get() throws InterruptedException, ExecutionException;  
    /** 
     * Waits if necessary for at most the given time for the computation 
     * to complete, and then retrieves its result, if available. 
     * 
     * @param timeout the maximum time to wait 
     * @param unit the time unit of the timeout argument 
     * @return the computed result 
     */  
    V get(long timeout, TimeUnit unit)  
        throws InterruptedException, ExecutionException, TimeoutException;  
}  

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

cancel()方法用來取消任務,如果取消任務成功則返回true,如果取消任務失敗則返回false。參數(shù)mayInterruptIfRunning表示是否允許取消正在執(zhí)行卻沒有執(zhí)行完畢的任務,如果設置true,則表示可以取消正在執(zhí)行過程中的任務。如果任務已經完成,則無論mayInterruptIfRunning為true還是false,此方法肯定返回false,即如果取消已經完成的任務會返回false;如果任務正在執(zhí)行,若mayInterruptIfRunning設置為true,則返回true,若mayInterruptIfRunning設置為false,則返回false;如果任務還沒有執(zhí)行,則無論mayInterruptIfRunning為true還是false,肯定返回true。

isCancelled()方法表示任務是否被取消成功,如果在任務正常完成前被取消成功,則返回 true。

isDone()方法表示任務是否已經完成,若任務完成,則返回true;

get()方法用來獲取執(zhí)行結果,這個方法會產生阻塞,會一直等到任務執(zhí)行完畢才返回;

get(long timeout, TimeUnit unit)用來獲取執(zhí)行結果,如果在指定時間內,還沒獲取到結果,就直接返回null。

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

  • 1)判斷任務是否完成;
  • 2)能夠中斷任務;
  • 3)能夠獲取任務執(zhí)行結果。

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

FutureTask

FutureTask的實現(xiàn):

public class FutureTask<V> implements RunnableFuture<V>

FutureTask類實現(xiàn)了RunnableFuture接口,RunnableFuture接口:

public interface RunnableFuture<V> extends Runnable, Future<V> {  
    /** 
     * Sets this Future to the result of its computation 
     * unless it has been cancelled. 
     */  
    void run();  
}  

可以看出RunnableFuture繼承了Runnable接口和Future接口,而FutureTask實現(xiàn)了RunnableFuture接口。所以它既可以作為Runnable被線程執(zhí)行,又可以作為Future得到Callable的返回值。
FutureTask提供了2個構造器:

public FutureTask(Callable<V> callable) {  
    if (callable == null)  
        throw new NullPointerException();  
    this.callable = callable;  
    this.state = NEW;       // ensure visibility of callable  
}  
public FutureTask(Runnable runnable, V result) {  
    this.callable = Executors.callable(runnable, result);  
    this.state = NEW;       // ensure visibility of callable  
}  

可以看到,Runnable注入會被Executors.callable()函數(shù)轉換為Callable類型,即FutureTask最終都是執(zhí)行Callable類型的任務。該適配函數(shù)的實現(xiàn)如下:

public static <T> Callable<T> callable(Runnable task, T result) {  
    if (task == null)  
        throw new NullPointerException();  
    return new RunnableAdapter<T>(task, result);  
} 

RunnableAdapter適配器

/** 
 * A callable that runs given task and returns given result 
 */  
static final class RunnableAdapter<T> implements Callable<T> {  
    final Runnable task;  
    final T result;  
    RunnableAdapter(Runnable task, T result) {  
        this.task = task;  
        this.result = result;  
    }  
    public T call() {  
        task.run();  
        return result;  
    }  
}  

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

FutureTask實現(xiàn)了Runnable,因此它既可以通過Thread包裝來直接執(zhí)行,也可以提交給ExecuteService來執(zhí)行。

FutureTask實現(xiàn)了Futrue可以直接通過get()函數(shù)獲取執(zhí)行結果,該函數(shù)會阻塞,直到結果返回。

實例:

Callable+Future獲取執(zhí)行結果

public class Test {
    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("主線程在執(zhí)行任務");
        try {
            System.out.println("task運行結果"+result.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        System.out.println("所有任務執(zhí)行完畢");
    }
}
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;
    }
}

執(zhí)行結果:

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

Callable+FutureTask獲取執(zhí)行結果

public class Test {
    public static void main(String[] args) {
        //第一種方式
        ExecutorService executor = Executors.newCachedThreadPool();
        Task task = new Task();
        FutureTask<Integer> futureTask = new FutureTask<Integer>(task);
        executor.submit(futureTask);
        executor.shutdown();
        //第二種方式,注意這種方式和第一種方式效果是類似的,只不過一個使用的是ExecutorService,一個使用的是Thread
        /*Task task = new Task();
        FutureTask<Integer> futureTask = new FutureTask<Integer>(task);
        Thread thread = new Thread(futureTask);
        thread.start();*/
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }
        System.out.println("主線程在執(zhí)行任務");
        try {
            System.out.println("task運行結果"+futureTask.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        System.out.println("所有任務執(zhí)行完畢");
    }
}
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;
    }
}

以上就是Future與FutureTask接口實現(xiàn)示例詳解的詳細內容,更多關于Future FutureTask接口實現(xiàn)的資料請關注腳本之家其它相關文章!

相關文章

  • JSON反序列化Long變Integer或Double的問題及解決

    JSON反序列化Long變Integer或Double的問題及解決

    這篇文章主要介紹了JSON反序列化Long變Integer或Double的問題及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-01-01
  • Java連接MYSQL數(shù)據(jù)庫的實現(xiàn)步驟

    Java連接MYSQL數(shù)據(jù)庫的實現(xiàn)步驟

    以下的文章主要描述的是java連接MYSQL數(shù)據(jù)庫的正確操作步驟,在此篇文章里我們主要是以實例列舉的方式來引出其具體介紹
    2013-06-06
  • Java集合ConcurrentHashMap詳解

    Java集合ConcurrentHashMap詳解

    ConcurrentHashMap?是?J.U.C?包里面提供的一個線程安全并且高效的?HashMap,所以ConcurrentHashMap?在并發(fā)編程的場景中使用的頻率比較高
    2023-01-01
  • 一文教你如何使用AES對接口參數(shù)進行加密

    一文教你如何使用AES對接口參數(shù)進行加密

    這篇文章主要是想為大家介紹一下如何使用AES實現(xiàn)對接口參數(shù)進行加密,文中的示例代碼簡潔易懂,具有一定的借鑒價值,需要的小伙伴可以了解一下
    2023-08-08
  • JavaWeb 使用Session實現(xiàn)一次性驗證碼功能

    JavaWeb 使用Session實現(xiàn)一次性驗證碼功能

    這篇文章主要介紹了JavaWeb 使用Session實現(xiàn)一次性驗證碼功能,本文通過實例代碼給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下
    2019-08-08
  • SpringMvc3+extjs4實現(xiàn)上傳與下載功能

    SpringMvc3+extjs4實現(xiàn)上傳與下載功能

    這篇文章主要為大家詳細介紹了SpringMvc3+extjs4實現(xiàn)上傳與下載功能,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-06-06
  • SpringMVC九大組件之HandlerMapping詳解

    SpringMVC九大組件之HandlerMapping詳解

    這篇文章主要介紹了SpringMVC九大組件之HandlerMapping詳解,HandlerMapping 叫做處理器映射器,它的作用就是根據(jù)當前 request 找到對應的 Handler 和 Interceptor,然后封裝成一個 HandlerExecutionChain 對象返回,需要的朋友可以參考下
    2023-09-09
  • IDEA 插件 mapper和xml互相跳轉操作

    IDEA 插件 mapper和xml互相跳轉操作

    這篇文章主要介紹了IDEA 插件 mapper和xml互相跳轉操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2021-02-02
  • JDBC連接MYSQL分步詳解

    JDBC連接MYSQL分步詳解

    JDBC是指Java數(shù)據(jù)庫連接,是一種標準Java應用編程接口(?JAVA?API),用來連接?Java?編程語言和廣泛的數(shù)據(jù)庫。從根本上來說,JDBC?是一種規(guī)范,它提供了一套完整的接口,允許便攜式訪問到底層數(shù)據(jù)庫,本篇文章我們來了解MySQL連接JDBC的流程方法
    2022-03-03
  • java必學必會之this關鍵字

    java必學必會之this關鍵字

    java必學必會之this關鍵字,java中this的用法進行了詳細的分析介紹,感興趣的小伙伴們可以參考一下
    2015-12-12

最新評論

苗栗市| 龙山县| 佛教| 久治县| 乌兰浩特市| 富蕴县| 农安县| 颍上县| 平度市| 红原县| 合肥市| 通州市| 信丰县| 宁海县| 方正县| 桐城市| 五峰| 芦山县| 池州市| 唐山市| 息烽县| 永新县| 沿河| 资兴市| 镇赉县| 景洪市| 青阳县| 麦盖提县| 德惠市| 天柱县| 巴林右旗| 惠州市| 鹿泉市| 自治县| 大石桥市| 峨眉山市| 沛县| 茶陵县| 正镶白旗| 石台县| 辉县市|