欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android线程专题:AsynchTask的使用场景及源码分析

程序员文章站 2022-07-02 10:33:16
AsynchTask简介 AsyncTask是个抽象类,支持UI线程的正确和轻松使用,允许你执行后台操作并且把结果推到UI线程,且不需要操作Thread和HandlerAsynchTask使用场景 理想状态下,AsynchTask应该用于短时操作(最多几秒钟)。如果你需要保留线程长时间运行,强烈建议你使ThreadPoolExecutorAsynchTask示例 class MyAsyncTask extends AsyncTask

AsynchTask简介

   AsyncTask是个抽象类,支持UI线程的正确和轻松使用,允许你执行后台操作并且把结果推到UI线程,且不需要操作Thread和Handler

AsynchTask使用场景

  理想状态下,AsynchTask应该用于短时操作(最多几秒钟)。如果你需要保留线程长时间运行,强烈建议你使ThreadPoolExecutor

AsynchTask示例

   class MyAsyncTask extends AsyncTask<String,Integer,String>{

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            Log.e(TAG, "onPreExecute: "+Thread.currentThread().getName());
        }

        @Override
        protected String doInBackground(String... strings) {
            Log.e(TAG, "doInBackground: "+Thread.currentThread().getName()+"//"+strings[0]+"//"+strings[1]);
            int progress=0;
            for (int i=0;i<=5;i++){
                progress+=20;
                publishProgress(progress);
            }
            return "执行结束";
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            Log.e(TAG, "onProgressUpdate: "+Thread.currentThread().getName()+"//"+values[0]);
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            Log.e(TAG, "onPostExecute: "+Thread.currentThread().getName()+s);
        }
    }



 private MyAsyncTask asyncTask;
        asyncTask = new MyAsyncTask();
        asyncTask.execute("开始了啊","第二个");

//运行结果
DemoActivity: onPreExecute: main
DemoActivity: doInBackground: AsyncTask #1//开始了啊//第二个
DemoActivity: onProgressUpdate: main//20
DemoActivity: onProgressUpdate: main//40
DemoActivity: onProgressUpdate: main//60
DemoActivity: onProgressUpdate: main//80
DemoActivity: onProgressUpdate: main//100
DemoActivity: onProgressUpdate: main//120
DemoActivity: onPostExecute: main执行结束

  1. AsynchTask是抽象类,使用它必须继承,且指定三个泛型参数,分别是Params, Progress, Result;Params是执行AsyncTask时需要传入的参数,可用于在后台任务中使用;Progress是后台任务执行时,如果需要在界面上显示当前的进度,则使用这里指定的泛型作为进度单位;Result当任务执行完毕后,如果需要对结果进行返回,则使用这里指定的泛型作为返回值类型
  2. onPreExecute、onProgressUpdate、onPostExecute运行在主线程​​​​​;onPreExecute最先执行,做准备工作;onProgressUpdate用来更新UI进度;onPostExecute时间节点是耗时操作执行结束后返回内容
  3. doInBackground运行在子线程,做耗时操作;可以通过publishProgress发送进度给onProgressUpdate,

源码分析

查看AsynchTask的构造函数

  private final WorkerRunnable<Params, Result> mWorker;
    private final FutureTask<Result> mFuture; 

public AsyncTask(@Nullable Looper callbackLooper) {
        mHandler = callbackLooper == null || callbackLooper == Looper.getMainLooper()
            ? getMainHandler()
            : new Handler(callbackLooper);

        mWorker = new WorkerRunnable<Params, Result>() {
            public Result call() throws Exception {
                mTaskInvoked.set(true);
                Result result = null;
                try {
                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
                    //noinspection unchecked
                    result = doInBackground(mParams);
                    Binder.flushPendingCommands();
                } catch (Throwable tr) {
                    mCancelled.set(true);
                    throw tr;
                } finally {
                    postResult(result);
                }
                return 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 static abstract class WorkerRunnable<Params, Result> implements Callable<Result> {
        Params[] mParams;
    }
  • 初始化中mWorker是Callable接口的实现类,跟FutureTask共同定义了线程,Callable线程详情

下一步是执行execute()

 private static volatile Executor sDefaultExecutor = SERIAL_EXECUTOR;
public static final Executor SERIAL_EXECUTOR = new SerialExecutor();


 @MainThread
    public final AsyncTask<Params, Progress, Result> execute(Params... params) {
        return executeOnExecutor(sDefaultExecutor, params);
    }

 @MainThread
    public final AsyncTask<Params, Progress, Result> executeOnExecutor(Executor exec,
            Params... params) {
        if (mStatus != Status.PENDING) {
            switch (mStatus) {
                case RUNNING:
                    throw new IllegalStateException("Cannot execute task:"
                            + " the task is already running.");
                case FINISHED:
                    throw new IllegalStateException("Cannot execute task:"
                            + " the task has already been executed "
                            + "(a task can be executed only once)");
            }
        }

        mStatus = Status.RUNNING;

        onPreExecute();

        mWorker.mParams = params;
        exec.execute(mFuture);

        return this;
    }

  @WorkerThread
    protected final void publishProgress(Progress... values) {
        if (!isCancelled()) {
            getHandler().obtainMessage(MESSAGE_POST_PROGRESS,
                    new AsyncTaskResult<Progress>(this, values)).sendToTarget();
        }
    }

  private static class InternalHandler extends Handler {
        public InternalHandler(Looper looper) {
            super(looper);
        }

        @SuppressWarnings({"unchecked", "RawUseOfParameterizedType"})
        @Override
        public void handleMessage(Message msg) {
            AsyncTaskResult<?> result = (AsyncTaskResult<?>) msg.obj;
            switch (msg.what) {
                case MESSAGE_POST_RESULT:
                    // There is only one result
                    result.mTask.finish(result.mData[0]);
                    break;
                case MESSAGE_POST_PROGRESS:
                    result.mTask.onProgressUpdate(result.mData);
                    break;
            }
        }
    }

 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);
            }
        }
    }  

 public static final Executor THREAD_POOL_EXECUTOR;

    static {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE_SECONDS, TimeUnit.SECONDS,
                sPoolWorkQueue, sThreadFactory);
        threadPoolExecutor.allowCoreThreadTimeOut(true);
        THREAD_POOL_EXECUTOR = threadPoolExecutor;
    }

  1. excute调用executeOnExecutor,首先执行onPreExecute()
  2. exec.execute(mFuture),是通过线程池执行是执行构造函数的变量mWorker内的call()方法,执行其中的doInBackground(mParams),最后执行postResult(result);
  3. 在AsynchTask实现类里的doInBackground中通过执行publishProgress传递进度;而传递是通过Handler发送,完成了子线程到主线程的切换
 private Result postResult(Result result) {
        @SuppressWarnings("unchecked")
        Message message = getHandler().obtainMessage(MESSAGE_POST_RESULT,
                new AsyncTaskResult<Result>(this, result));
        message.sendToTarget();
        return result;
    }

 private static class InternalHandler extends Handler {
        public InternalHandler(Looper looper) {
            super(looper);
        }

        @SuppressWarnings({"unchecked", "RawUseOfParameterizedType"})
        @Override
        public void handleMessage(Message msg) {
            AsyncTaskResult<?> result = (AsyncTaskResult<?>) msg.obj;
            switch (msg.what) {
                case MESSAGE_POST_RESULT:
                    // There is only one result
                    result.mTask.finish(result.mData[0]);
                    break;
                case MESSAGE_POST_PROGRESS:
                    result.mTask.onProgressUpdate(result.mData);
                    break;
            }
        }
    }

private void finish(Result result) {
        if (isCancelled()) {
            onCancelled(result);
        } else {
            onPostExecute(result);
        }
        mStatus = Status.FINISHED;
    }


  private static class AsyncTaskResult<Data> {
        final AsyncTask mTask;
        final Data[] mData;

        AsyncTaskResult(AsyncTask task, Data... data) {
            mTask = task;
            mData = data;
        }
    }
  1. doBackground执行后,最终调用AsynchTask的finish方法,然后调用onPostExecute完成整个流程

总结:使用场景是短时异步执行,UI更新操作

 

本文地址:https://blog.csdn.net/qq_30359699/article/details/107186534