1. 程式人生 > >java裡面的FutureTask簡單使用(配合原始碼講解)

java裡面的FutureTask簡單使用(配合原始碼講解)

最近無意間看到了關於AsyncTask的一篇分析文章AsyncTask原始碼分析,記得很早之前還看過郭神部落格裡面分析了AsyncTask原始碼。去檢視AsyncTask原始碼會發現裡面使用了FutureTask在它自己的建構函式裡面,我的sdkandroid-23裡面檢視的。

 /**
     * Creates a new asynchronous task. This constructor must be invoked on the UI thread.
     */
    public AsyncTask() {
        // 這裡注意它實現了Callable
        mWorker = new
WorkerRunnable<Params, Result>() { public Result call() throws Exception { mTaskInvoked.set(true); Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); //noinspection unchecked Result result = doInBackground(mParams); Binder.flushPendingCommands(); return
postResult(result); } }; // 這裡使用了FutureTask mFuture = new FutureTask<Result>(mWorker) { @Override protected void done() { try { postResultIfNotInvoked(get()); } catch (InterruptedException e) { android.util.Log.w(LOG_TAG, e); } catch
(ExecutionException e) { throw new RuntimeException("An error occurred while executing doInBackground()", e.getCause()); } catch (CancellationException e) { postResultIfNotInvoked(null); } } }; }

其實這裡把CallableFutureTask2個比較重要的傢伙弄懂,就能知道AsyncTask大致是怎麼實現的了。進入原始碼去看發現它們都是java提供的用來實現java併發程式設計的。
先具體看下Callable的程式碼:

public interface Callable<V> {
    /**
     * Computes a result, or throws an exception if unable to do so.
     *
     * @return computed result
     * @throws Exception if unable to compute a result
     */
    V call() throws Exception;
}

從程式碼註釋很明顯可以看出,是返回一個結果,那也表明我們可以在裡面進行一些耗時操作之後(比如網路通訊或者是資料庫操作等等),然後在返回計算好之後的結果。

  private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> {
        Params[] mParams;
    }

// 這裡在call裡面doInBackground
 mWorker = new WorkerRunnable<Params, Result>() {
            public Result call() throws Exception {
                mTaskInvoked.set(true);

                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
                //noinspection unchecked
                Result result = doInBackground(mParams);
                Binder.flushPendingCommands();
                return postResult(result);
            }
        };

可以看到WorkerRunnable也是實現了Callable,然後裡面呼叫了doInBackground
然後我們再去看下FutureTask程式碼:

public class FutureTask<V> implements RunnableFuture<V> 
public interface RunnableFuture<V> extends Runnable, Future<V> {
    /**
     * Sets this Future to the result of its computation
     * unless it has been cancelled.
     */
    void run();
}
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 {@code cancel} is called,
     * this task should never run.  If the task has already started,
     * then the {@code mayInterruptIfRunning} parameter determines
     * whether the thread executing this task should be interrupted in
     * an attempt to stop the task.
     *
     * <p>After this method returns, subsequent calls to {@link #isDone} will
     * always return {@code true}.  Subsequent calls to {@link #isCancelled}
     * will always return {@code true} if this method returned {@code true}.
     *
     * @param mayInterruptIfRunning {@code true} if the thread executing this
     * task should be interrupted; otherwise, in-progress tasks are allowed
     * to complete
     * @return {@code false} if the task could not be cancelled,
     * typically because it has already completed normally;
     * {@code true} otherwise
     */
    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();

    /**
     * Returns {@code true} if this task completed.
     *
     * Completion may be due to normal termination, an exception, or
     * cancellation -- in all of these cases, this method will return
     * {@code true}.
     *
     * @return {@code true} if this task completed
     */
    boolean isDone();

    /**
     * Waits if necessary for the computation to complete, and then
     * retrieves its result.
     *
     * @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
     */
    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
     * @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;
}

程式碼不多,算是比較簡單的吧。
為了深刻理解它具體的運用,那我們自己write simple(喪心病狂) code。

 private static class RealData implements Callable<String> {

        @Override
        public String call() throws Exception {
            //這裡是真實的業務邏輯,耗時很長
            StringBuffer stringBuffer = new StringBuffer();
            for (int i = 0; i < 10; i++) {
                stringBuffer.append(i);
                //模擬一段耗時操作
                SystemClock.sleep(1 * 1000);
            }

            return stringBuffer.toString();
        }
    }

    private void testCallable() {
        FutureTask<String> futureTask = new FutureTask<String>(new RealData()) {
            @Override
            protected void done() {
                //FutureTask執行完的回撥
                try {
                    // FutureTask的get()是一個同步方法,會有時間等待,最好避免在主執行緒執行
                    String str = get();
                    System.out.println();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
                doSomething();
            }
        };
        //自定義ExecutorService,我會在後面的文章中總結。
        ExecutorService executor = Executors.newFixedThreadPool(1);
        //在這裡執行RealData的call內容
        executor.submit(futureTask);
        System.out.println();
    }

    private void doSomething() {
        System.out.println();
    /*執行回撥結果*/
    }

好了簡單的示例程式碼寫好了,在call裡面處理耗時並且返回結果,然後在done裡面通過get拿到獲取的結果,就可以利用Handler通知主執行緒更新UI了。還記得AsyncTask建構函式裡面的程式碼麼:

public AsyncTask() {
        mWorker = new WorkerRunnable<Params, Result>() {
            public Result call() throws Exception {
                mTaskInvoked.set(true);

                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
                //noinspection unchecked
                Result result = doInBackground(mParams);
                Binder.flushPendingCommands();
                return postResult(result);
            }
        };

        mFuture = new FutureTask<Result>(mWorker) {
            @Override
            protected void done() {
                try {
                    postResultIfNotInvoked(get());
                } catch (InterruptedException e) {
                    android.util.Log.w(LOG_TAG, e);
                } catch (ExecutionException e) {
                    throw new RuntimeException("An error occurred while executing doInBackground()",
                            e.getCause());
                } catch (CancellationException e) {
                    postResultIfNotInvoked(null);
                }
            }
        };
    }

    private void postResultIfNotInvoked(Result result) {
        final boolean wasTaskInvoked = mTaskInvoked.get();
        if (!wasTaskInvoked) {
            postResult(result);
        }
    }

    private Result postResult(Result result) {
        @SuppressWarnings("unchecked")
        Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
                new AsyncTaskResult<Result>(this, result));
        message.sendToTarget();
        return result;
    }

它也是在done裡面利用Handler傳送Message去更新UI的。好了簡單滴記錄一下,今天就先這樣吧!!!