AsyncTask 创建以及其方法在哪个线程中执行

自定义的AsyncTask:

class ThreadTask : AsyncTask() {

override fun onPreExecute() {
    super.onPreExecute()
    Log.e("ThreadTask-->","onPreExecute thread is ${Thread.currentThread()}")
}

override fun onPostExecute(result: Int?) {
    super.onPostExecute(result)
    Log.e("ThreadTask-->","onPostExecute thread is ${Thread.currentThread()}")
}

override fun doInBackground(vararg params: Void?): Int {
    Log.e("ThreadTask-->","doInBackground thread is ${Thread.currentThread()}")

    return 0
}
}

调用:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    AnnotationParse.parse(this);

    Log.e("MainActivity-->", "current thread is " + Thread.currentThread());
    new Thread(new Runnable() {
        @Override
        public void run() {
            Log.e("MainActivity-->", "current thread is " +  Thread.currentThread());
            new ThreadTask().execute();
        }
    }).start();
}

对应的Log:


image.png

execute() 方法执行在 Thread[Thread-1787,5,main] 中,onPreExecute() 方法执行在Thread[Thread-1787,5,main]中,doInBackground()方法在Thread[AsyncTask #1,5,main]线程中--子线程,onPostExecute执行在主线程Thread[main,5,main]

注意到 onPreExecute()方法执行在 execute() 所在的线程中,onPostExecute 在主线程中执行,而 doInBackground()在子线程(后台线程)中执行。因为在 AsyncTask 构造方法中 doInBackground() 在后台线程FutureTask(Runnable类型) 中执行,并且也设置了线程优先级(Process.THREAD_PRIORITY_BACKGROUND)。

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

    mWorker = new WorkerRunnable() {
        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(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);
            }
        }
    };
}

你可能感兴趣的:(AsyncTask 创建以及其方法在哪个线程中执行)