简体   繁体   中英

Android AsyncTask - How does it work?

As per my understanding, threads communicate by shared resources eg a BlockingQueue. When the thread which is waiting to receive message from the other, it will block while access the queue util the other thread gives up the lock.

However, in Android AsyncTask, It seems UI thread (receiver) doesn't have to block while waiting for the message from the other thread.

private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
     protected Long doInBackground(URL... urls) {
         int count = urls.length;
         long totalSize = 0;
         for (int i = 0; i < count; i++) {
             totalSize += Downloader.downloadFile(urls[i]);
             publishProgress((int) ((i / (float) count) * 100));
             // Escape early if cancel() is called
             if (isCancelled()) break;
         }
         return totalSize;
     }

     protected void onProgressUpdate(Integer... progress) {
         setProgressPercent(progress[0]);
     }

     protected void onPostExecute(Long result) {
         showDialog("Downloaded " + result + " bytes");
     }
 }

The callback onProgressUpdate() seems to be invoked from no where without blocking UI thread. Where am I missing?

In a nutshell: The main thread executes tasks from a queue, and sits idle whenever the queue is empty. When an AsyncTask finishes its background work, it puts a task in the main thread's queue. That task is to call onPostExecute(...) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM