Java – is it normal that the asynctask thread still exists after execution?

When I use asynctasks check in DDMS, is it normal for the thread to remain in memory as a waiting thread after onpostexecute() method? This is a simplified activity that can reproduce my question:

package com.example.async;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;

public class ASyncTaskExampleActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    new ExampleAsyncTask().execute();
}


private class ExampleAsyncTask extends AsyncTask<Void,Void,Void> {

    @Override
    protected Void doInBackground(Void... params) {
        for (int i =0; i<50000;i++){
            int j=i*2;
        }
        return null;
    }

    protected void onPostExecute(Void result) {
        Log.d("Test","End onPostExecute");
     }

}

}

Solution

Asynctask uses "thread pool" technology Each asynctask you start will enter the queue; There are some idle threads in the pool (or create them as needed until a limit) waiting for tasks The idle thread in the pool gets the asynctask and executes it, and then returns to the pool Then repeat the process until there are no more tasks in the queue

This approach has two important features:

>Each time a thread is created, there is no overhead > in the case of a large number of tasks, the system performance will degrade gracefully: most tasks will wait in the queue, and only a few of them will be executed at one time; Eventually everyone will be executed Otherwise, if a separate thread is started for each task, the system may run out of memory or threads, or the task will complete forever

The threads you see in DDMS after asynctask is completed are idle threads in the pool

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>