Asynctask原理分析

作者: 上官若枫 | 来源:发表于2018-07-26 21:52 被阅读9次

    Asynctask是一种轻量级异步任务类,任务是在线程池中执行后台任务的,并将结果返回到UI界面。它封装了handler和thread,但是asynctask不适合特别耗时的任务,耗时任务建议使用线程池。

    1.方法介绍

    核心方法四个:onPreExecute()doInBackground()onProgressUpdate()onPostExecute(),这四个方法除了doInBackground()其余都存在了主线程

    2.注意点

    1)Asynctask类初始加载应该在主线程,android5.0以后activitythread的main方法中,已经将这个类初始化了
    2)Asynctask创建对象,也应该在主线程
    3)execute方法要在主线程
    4)不能手动调用asynctask的四个核心方法
    5)一个Asynctask对象,只能调用一次execute方法
    6)android1.6以前是串行,3.0以后既可以串行也可以并行

    3.源码分析

    Asynctask原理图

    首先来解释一下,刚创建完成asynctask对象后,会执行execute()方法,然后执行onpreExecute(),接下来asynctask里面的线程池就开始工作了。在Asynctask创建的同时,会将doInBackground()这个方法体封装进一个callable当中,然后再进行封转到并发类Futuretask中,代码如下:

     /**
         * Creates a new asynchronous task. This constructor must be invoked on the UI thread.
         */
        public AsyncTask() {
            mWorker = new WorkerRunnable<Params, Result>() {
                public Result call() throws Exception {
                    mTaskInvoked.set(true);
    
                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
                    //noinspection unchecked
                    return postResult(doInBackground(mParams));
                }
            };
    
            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 occured while executing doInBackground()",
                                e.getCause());
                    } catch (CancellationException e) {
                        postResultIfNotInvoked(null);
                    }
                }
            };
        }
    

    线程池在执行execute方法的时候,会先将任务添加到队列中,如果当前没有活动的任务,就会执行scheduleNext()来执行下一个任务。从这一个角度来看,asynctask是串行的。代码如下:

     private static class SerialExecutor implements Executor {
            final ArrayDeque<Runnable> mTasks = new ArrayDeque<Runnable>();
            Runnable mActive;
    
            public synchronized void execute(final Runnable r) {
                mTasks.offer(new Runnable() {
                    public void run() {
                        try {
                            r.run();
                        } finally {
                            scheduleNext();
                        }
                    }
                });
                if (mActive == null) {
                    scheduleNext();
                }
            }
    
            protected synchronized void scheduleNext() {
                if ((mActive = mTasks.poll()) != null) {
                    THREAD_POOL_EXECUTOR.execute(mActive);
                }
            }
        }
    

    在执行Futuretask的run方法的时候,最后会调用到WorkerRunnable的call方法,进而执行doinbackground方法,会把返回值传给postResult方法,它会通过sHandler发送一个消息,handler处理消息会让Asynctask执行finish方法

     private Result postResult(Result result) {
            @SuppressWarnings("unchecked")
            Message message = sHandler.obtainMessage(MESSAGE_POST_RESULT,
                    new AsyncTaskResult<Result>(this, result));
            message.sendToTarget();
            return result;
        }
    
    这里又涉及到handler切换线程的工作,我这里再来讲解一下,postresult是在WorkerRunnable中调用的,而WorkerRunnable又被封装进了FutureTask,要知道这个类是一个runnable也就是说它是一个线程,而Asynctask是创建在主线程中的,这不就是两个线程的切换吗???在runnable中调用了handler,而handler创建在了主线程中,这就直接切换到了主线程。

    相关文章

      网友评论

        本文标题:Asynctask原理分析

        本文链接:https://www.haomeiwen.com/subject/rulbmftx.html