Asynctask实现源码分析

<pre name="code" class="java"><pre name="code" class="java">Asynctask实现(源代码2.2)


使用:
	1.继承并实现Asynctask,实现类DownloadFilesTask
	2.新建对象,并调用execute。new DownloadFilesTask().execute(param);

入口1:继承并实现Asynctask,实现类DownloadFilesTask

    /**
     * Creates a new asynchronous task. This constructor must be invoked on the UI thread.
     	主要完成步骤2:构造一个Runnable的异步任务(FutrueTAsk)
     */
    public AsyncTask() {
    	// 1.实现callable接口,作为FutureTask构造参数
        mWorker = new WorkerRunnable<Params, Result>() {
            public Result call() throws Exception {
                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
                return doInBackground(mParams);
            }
        };

        // 2.未来任务(实现Runnable接口),作为线程池调用execute(Runnable)的参数
        // A FutureTask can be used to wrap a Callable or Runnable object. Because FutureTask implements Runnable, 
        // a FutureTask can be submitted to an Executor for execution. 对Runnable/Callable接口的包装,可当做Runnable使用
        mFuture = new FutureTask<Result>(mWorker) {	// FutureTask实现runnable接口
            // 4
            @Override
            protected void done() {
                Message message;
                Result result = null;
               
                result = get();	// 调用Sync.innerGet获得donInBackGroud执行结果(之前在Sync中通过innerSet保存执行结果)
               	// 5
                message = sHandler.obtainMessage(MESSAGE_POST_RESULT,
                        new AsyncTaskResult<Result>(AsyncTask.this, result));
                        //AsyncTaskResult类包装AsyncTask对象和doInBackground执行结果

                message.sendToTarget();
            }
        };
    }

    private static final InternalHandler sHandler = new InternalHandler();

    private static class InternalHandler extends Handler {
        @SuppressWarnings({"unchecked", "RawUseOfParameterizedType"})
        @Override
        public void handleMessage(Message msg) {
            AsyncTaskResult result = (AsyncTaskResult) msg.obj;
            switch (msg.what) {
                case MESSAGE_POST_RESULT:
                	// 6
                    // There is only one result
                    result.mTask.finish(result.mData[0]);	// 内部调用onPostExecute(result);
                    break;
                case MESSAGE_POST_PROGRESS:
                    result.mTask.onProgressUpdate(result.mData);	// 更新过程结果
                    break;
                case MESSAGE_POST_CANCEL:
                    result.mTask.onCancelled();
                    break;
            }
        }
    }


入口2:新建对象,并调用execute。new DownloadFilesTask().execute(param);
    public final AsyncTask<Params, Progress, Result> execute(Params... params) {     
    	// 1
        onPreExecute();	// 回调用户接口:在异步任务执行前执行

        mWorker.mParams = params;	// 参数封装在mWorker中
        sExecutor.execute(mFuture);	// 子线程中执行,即调用mFuture的runnable方法

        return this;
    }



小结:Asynctask==线程池(管理所有Thread)+Handler
     本来实现很简单,只要线程Runnable接口实现+Handler即可实现,但是为了获取Runnable执行结果,增强了Runnable接口,改成Callable接口.
这样,Asynctask将T doInBackGround(Param)封装在Callable中,并由call调用,在FutureTask中对Runnable进行封装,run函数调用
Callable.call(既:调用doInBackGround),调用完成后调用done钩子函数,而done钩子函数在AsyncTask中实现,调用Asynctask中对handler发送消息		</span>在消息体中封装Callable.call的执行结果给handleMessage中的onPostExecute(Result),从而在UI线程中执行<span style="font-family: Arial, Helvetica, sans-serif;">	</span>
	主要涉及对象:
		AsyncTask调用FutureTask(增强Runnable接口),FutureTask调用WorkerRunnable,WorkerRunnable访问AsyncTask回调接口
		三者关系如下:AsyncTask含有FutureTask,FutureTask含有Sync和WorkerRunnable(封装异步任务)
AsyncTask:E
		FutureTask实现Runnable接口,封装成callable接口(带返回参数的run方法,既:增强run方法功能,并把结果保存起来,可供外界获取)
			Sync:FutureTask的代理类
		WorkerRunnable:封装Callable接口,供FutureTask使用

    调用过程:Asynctask.execute-->线程池执行FutureTask(实现Runnable接口)-->WorkerRunnable(封装Callable接口)-->doInBackground-->
        获取到返回值后设置返回值-->发送消息(UI线程)-->调用onPostExecute(设置的结果返回值)





补充:FutureTask实现
 内部类Sync作用:代理执行FutureTask的任务,并且保存线程执行结果。本质就是FutureTask的代理类
 class FutureTask<V> implements Future<V>, Runnable {

	public FutureTask(Callable<V> callable) {	// callable为AsyncTAsk的mWorker,内部有用户业务逻辑doInBackground
        sync = new Sync(callable);	// sync为FutureTask内部类,FutureTask的逻辑大部分都在Sync内部类中
    }

    // 2
	public void run() {
        sync.innerRun();	
    }

    class Sync extends AbstractQueuedSynchronizer {	// 可以控制线程执行取消等操作
    	Callable callable;

        void innerRun() {       
            runner = Thread.currentThread();
            // 将执行结果(doInBackground),保存在Sync中
            innerSet(callable.call());    // callable.call():调用外部传入的Asnctask的mWorker的doInBackground       
        }

        // 3
        void innerSet(V v) {     
            result = v;	// doInBackground执行结果保存在result中
     
            done();	// 钩子函数,回调FutureTask的done方法。在AsyncTask的构造中,实现了FutureTask的done方法
        }

       V innerGet(long nanosTimeout) throws InterruptedException, ExecutionException, TimeoutException {     
            return result;
        }

    }

 }








 

                
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值