Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Thực thi AsyncTask song song (Parallel Execution) trong Android

Giới thiệu

Mặc định AsyncTask chạy tuần tự (serial) trên Android 3.0+. Để chạy song song, dùng executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params). Tối đa 5 task cùng lúc.

⚠️ DEPRECATED: AsyncTask deprecated API 30. Dùng ExecutorService, Coroutines, WorkManager, RxJava thay thế.

Bước 1: Tạo dự án mới

Android Studio → File → New Project.

Bước 2: Giao diện (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:id="@+id/rootview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="#C1C1C1"
    android:gravity="center_horizontal"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/asyncTask"
        android:text="Tải 2 ảnh song song"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <ImageView
        android:id="@+id/image"
        android:layout_width="300dp"
        android:layout_height="300dp" />

    <ImageView
        android:id="@+id/image2"
        android:layout_width="300dp"
        android:layout_height="300dp" />

</LinearLayout>

Bước 3: 2 AsyncTask chạy song song (src/MainActivity.java)

package com.example.andy.myapplication;

import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity {
    URL imageUrl = null;
    InputStream is = null;
    Bitmap bmImg = null;
    ImageView imageView, imageView2;
    DownloadTask task1, task2;
    ProgressDialog progressDialog;

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

        Button button = findViewById(R.id.asyncTask);
        imageView = findViewById(R.id.image);
        imageView2 = findViewById(R.id.image2);

        button.setOnClickListener(v -> {
            task2 = new DownloadTask2();
            task2.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, 
                "https://www.tutorialspoint.com/cprogramming/images/logo.png");

            task1 = new DownloadTask();
            task1.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, 
                "https://www.tutorialspoint.com/images/tp-logo-diamond.png");
        });
    }

    private class DownloadTask extends AsyncTask {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressDialog = new ProgressDialog(MainActivity.this);
            progressDialog.setMessage("Đang tải ảnh 1...");
            progressDialog.setIndeterminate(true);
            progressDialog.setCancelable(false);
            progressDialog.show();
        }

        @Override
        protected Bitmap doInBackground(String... urls) {
            try {
                imageUrl = new URL(urls[0]);
                HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
                conn.setDoInput(true);
                conn.connect();
                is = conn.getInputStream();
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inPreferredConfig = Bitmap.Config.RGB_565;
                bmImg = BitmapFactory.decodeStream(is, null, options);
            } catch (IOException e) { e.printStackTrace(); }
            return bmImg;
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
            if (imageView != null) {
                progressDialog.dismiss();
                imageView.setImageBitmap(bitmap);
            }
        }
    }

    private class DownloadTask2 extends AsyncTask {
        @Override
        protected Bitmap doInBackground(String... urls) {
            try {
                imageUrl = new URL(urls[0]);
                HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
                conn.setDoInput(true);
                conn.connect();
                is = conn.getInputStream();
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inPreferredConfig = Bitmap.Config.RGB_565;
                bmImg = BitmapFactory.decodeStream(is, null, options);
            } catch (IOException e) { e.printStackTrace(); }
            return bmImg;
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
            if (imageView2 != null) {
                imageView2.setImageBitmap(bitmap);
            }
        }
    }
}

Giải thích executeOnExecutor

task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
  • THREAD_POOL_EXECUTOR: Thread pool mặc định (core 5 threads, max 128)
  • SERIAL_EXECUTOR: Mặc định (chạy tuần tự)
  • Tối đa 5 task chạy đồng thời, các task khác đợi trong queue

Manifest (Internet permission)

<uses-permission android:name="android.permission.INTERNET"/>

Chạy ứng dụng

Chạy app → Nhấn Button → 2 ProgressDialog/ảnh tải song song → 2 ImageView hiển thị ảnh khi xong.

Cách hiện đại: ExecutorService

ExecutorService executor = Executors.newFixedThreadPool(5);
executor.execute(() -> {
    // Background work
    runOnUiThread(() -> imageView.setImageBitmap(bitmap));
});