Java Future 和 FutureTask 源碼Demo


 Future 是一個接口,看源碼有Future 和 FutreTask 使用Demo

package java.util.concurrent;

/**
 * A <tt>Future</tt> represents the result of an asynchronous
 * computation.  Methods are provided to check if the computation is
 * complete, to wait for its completion, and to retrieve the result of
 * the computation.  The result can only be retrieved using method
 * <tt>get</tt> when the computation has completed, blocking if
 * necessary until it is ready.  Cancellation is performed by the
 * <tt>cancel</tt> method.  Additional methods are provided to
 * determine if the task completed normally or was cancelled. Once a
 * computation has completed, the computation cannot be cancelled.
 * If you would like to use a <tt>Future</tt> for the sake
 * of cancellability but not provide a usable result, you can
 * declare types of the form {@code Future<?>} and
 * return <tt>null</tt> as a result of the underlying task.
 *
 * <p>
 * <b>Sample Usage</b> (Note that the following classes are all
 * made-up.) <p>
 *  <pre> {@code
 * interface ArchiveSearcher { String search(String target); } * class App { * ExecutorService executor = ... * ArchiveSearcher searcher = ... * void showSearch(final String target) * throws InterruptedException { * Future<String> future * = executor.submit(new Callable<String>() { * public String call() { * return searcher.search(target); * }}); * displayOtherThings(); // do other things while searching * try { * displayText(future.get()); // use future * } catch (ExecutionException ex) { cleanup(); return; } * } * }}</pre>
 *
 * The {@link FutureTask} class is an implementation of <tt>Future</tt> that
 * implements <tt>Runnable</tt>, and so may be executed by an <tt>Executor</tt>.
 * For example, the above construction with <tt>submit</tt> could be replaced by:
 *  <pre> {@code
 *     FutureTask<String> future = * new FutureTask<String>(new Callable<String>() { * public String call() { * return searcher.search(target); * }}); * executor.execute(future);}</pre>
 *
 * <p>Memory consistency effects: Actions taken by the asynchronous computation
 * <a href="package-summary.html#MemoryVisibility"> <i>happen-before</i></a>
 * actions following the corresponding {@code Future.get()} in another thread.
 *
 * @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> {

 

 1:測試類 App.

package com.future;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;

public class App {
    static ExecutorService executor = null;
    static ArchiveSearcher searcher = null;

    public static void main(String[] args) {
        executor = Executors.newSingleThreadScheduledExecutor();
        searcher = new ArchiveSearcherImp();

        try {
            showSearch("hello");
            //showSearch2("world");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    
    static void showSearch(final String target) throws InterruptedException {
        Future<String> future = executor.submit(new Callable<String>() {
            public String call() {
                return searcher.search(target);
            }
        });
        System.out.println("displayOtherThings");
        //boolean c = future.cancel(true);
        // do other things while searching
        try {
            System.out.println("displayText(" + future.get() + ")");
        } catch (Exception ex) {
            System.out.println("Future Canceled:" + future.isCancelled());
            return;
        }
    }

    static void showSearch2(final String target) throws InterruptedException {
        FutureTask<String> future = new FutureTask<String>(
                new Callable<String>() {
                    public String call() {
                        return searcher.search(target);
                    }
                });
        executor.execute(future);
    }

}
View Code

2:接口類 

package com.future;

public interface ArchiveSearcher {
    String search(String target);
}
View Code

3:接口實現類

package com.future;

public class ArchiveSearcherImp implements ArchiveSearcher {

    public String search(String target) {
        // TODO Auto-generated method stub
        System.out.println("ArchiveSearcherImp:" + target);
        return target + "End ";
    }

}
View Code

這樣小Demo就跑完了,幫助我們理解, 

 

區別:(應用來自http://blog.csdn.net/naughty610/article/details/38961675)

Future是一個接口,代表可以取消的任務,並可以獲得任務的執行結果

FutureTask 是基本的實現了Future和runnable接口
           實現runnable接口,說明可以把FutureTask實例傳入到Thread中,在一個新的線程中執行。
           實現Future接口,說明可以從FutureTask中通過get取到任務的返回結果,也可以取消任務執行(通過interreput中斷)

 

cancel方法用來取消任務,如果取消任務成功則返回true,如果取消任務失敗則返回false .

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

 

isDone

 

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

 


免責聲明!

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



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