java 異步任務與結果

Callable, Future, FutureTask

Callable 與Runnable

Runnable 介紹

Runnable只是一個接口,它可以被任何類繼承,它的實例通過線程執行

Callable 與Runnable區別
代碼
public interface Runnable {

    public abstract void run();
}
作用:
  1. 當做線程使用
  2. 當做任務被線程執行。
特點
  1. 當做任務沒有時run()方法沒有返回值;
  2. 不能拋出異常;
Callable 介紹
源碼
public interface Callable<V> {

    V call() throws Exception;
}

Callable是一個任務接口,它定義了一個帶有返回值的並且拋出異常的任務。

作用
  1. 當做任務
特點
  1. 方法call() 具有返回值
  2. 可拋出異常,支持泛型

Future

future 介紹

future 代表異步操作運算的結果,它也是一個接口;
常用於獲取運行結果,查詢是否完成,對任務結果進行取消

public interface Future<V> {

    /**

       嘗試取消當前任務,如果任務已經被完成,這個操作就失敗返回fail,    
       參數 mayInterruptIfRunning 爲ture 時,代表任務在執行中,也可以取消任務; 爲false時,只能取消未被執行的任務。

     */
    boolean cancel(boolean mayInterruptIfRunning);

    /**
     * Returns {@code true} if this task was cancelled before it completed
     * normally.
     *
     * @return {@code true} if this task was cancelled before it completed
     */
    boolean isCancelled();

    /**
     返回任務是否完成。
     *
     * @return {@code true} if this task completed
     */
    boolean isDone();

    /**
     * 獲取返回結果,有必要一直等在結果返回;
     */
    V get() throws InterruptedException, ExecutionException;

    /**
     * 獲取執行結果,有必要就等待timeout , 指定時間內結果沒有執行完,返回Null
     *
     * @param timeout the maximum time to wait
     * @param unit the time unit of the timeout argument
     * @return the computed result
     * @throws CancellationException if the computation was cancelled
     * @throws ExecutionException if the computation threw an
     * exception
     * @throws InterruptedException if the current thread was interrupted
     * while waiting
     * @throws TimeoutException if the wait timed out
     */
    V get(long timeout, TimeUnit unit)
        throws InterruptedException, ExecutionException, TimeoutException;
}
功能
  1. 取消任務
  2. 獲取任務執行結果
  3. 判斷任務是否完成

FutureTask

簡述

FutureTask 是一個類,

部分源碼
public class FutureTask<V> implements RunnableFuture<V> {
.....

}
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,它既可以當做任務被執行,又可以判斷結果是完成,但獲取不到具體的值,因爲它的父類是Callable 而不是Runnable。

FutureTask 是RunnableFuture 的子類實現。

示例

public class AsyncTask {

    public static void main(String args[]) throws InterruptedException, ExecutionException {

        ExecutorService service = Executors.newCachedThreadPool();
        MyTask1 task1 = new MyTask1();

        Future<String> result1 = service.submit(task1);
        System.out.println("...等待完成任務1。。執行結果是:" + result1.get());

        MyTask2 task2 = new MyTask2();
        Future<?> result2 = service.submit(task2);
        System.out.println("...等待完成任務2.。執行結果是。" + result2.get());

        FutureTask<String> ft = new FutureTask<String>(task1);

        Future<String> reuslt2 = (Future<String>) service.submit(ft);

        System.out.println("...等待任務3.。執行結果是:" + result2.get());

        service.shutdown();

    }


}

class MyTask2 implements Runnable {

    @Override
    public void run() {

        System.out.println("..執行Runnable任務。。");

    }

}


class MyTask1 implements Callable<String> {

    @Override
    public String call() throws Exception {
        System.out.println("...線程執行callable任務。");
        return "success";
    }

}
執行結果
...線程執行callable任務。
...等待完成任務1。。執行結果是:success
..執行Runnable任務。。
...等待完成任務2.。執行結果是。null
...等待任務3.。執行結果是:null
...線程執行callable任務。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章