AsyncTask的线程仍然存在执行后,这是否正常? [英] AsyncTask thread still there after execute, is that normal?

查看:202
本文介绍了AsyncTask的线程仍然存在执行后,这是否正常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用AsyncTasks检查在DDMS,线程保存在内存中的onPostExecute()方法后等待的线程,这是否正常?下面是转载我的问题一个简单的活动:

when I use AsyncTasks checking in the DDMS, the thread persist in memory as waiting thread after the onPostExecute() method, is that normal?. Here is a simplified Activity that reproduces my problem:

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

}

}

推荐答案

AsyncTask的使用线程池技术。你开始每个AsyncTask的进入队列;有一些空闲线程中的池(或它们根据需要达到一定的极限创建)等待的任务。从池中的空闲线程需要你的AsyncTask并执行它,然后返回到池中。然后,该过程重复,直到没有更多的任务在队列中。

AsyncTask uses "thread pool" technique. Each AsyncTask you start gets into a queue; there are some idle threads in the "pool" (or they are created as needed up to a certain limit) waiting for tasks. An idle thread from the pool takes your AsyncTask and executes it, then returns to the pool. Then the process repeats until there are no more tasks in the queue.

该方法具有两个重要的特点:

This approach has 2 important features:

  1. 无开销创建线程每次
  2. 在的情况下的巨大任务数的系统性能下降的正常:大部分的任务将在队列中等待,只有少数人会 可以在一个时间执行;最终他们都将得到执行。 否则,如果一个单独的线程开始为每个任务,所述 系统可能会耗尽内存或线程,或任务将 永远结束。
  1. no overhead for creating a thread every time
  2. in case of huge number of tasks system performance degrades gracefully: most of the tasks will wait in the queue and only few of them will be executed at a time; eventually all of them will get executed. Otherwise, if a separate thread was started for each task, the system would likely run out of memory or threads, or tasks will take forever to finish.

你你的AsyncTask结束后,在DDMS看到的线程池中的空闲线程。

The thread which you see in DDMS after your AsyncTask finished is the idle thread in the pool.

这篇关于AsyncTask的线程仍然存在执行后,这是否正常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆