AsyncTask 线程永远不会死

我使用 AsyncTask来获取用户按下按钮时的响应数据。这种方法运行良好,并且在获取数据时保持接口响应,但是当我检查 Eclipse 调试器中发生了什么时,我发现每次创建一个新的 AsyncTask(这种情况很常见,因为它们只能使用一次) ,都会创建一个新的线程,但是从未终止。

结果就是大量的 AsyncTask线程只是停留在那里。我不确定这在实践中是否是一个问题,但我真的想摆脱这些额外的线程。

我怎样才能杀死这些线?

34262 次浏览

AsyncTask manages a thread pool, created with ThreadPoolExecutor. It will have from 5 to 128 threads. If there are more than 5 threads, those extra threads will stick around for at most 10 seconds before being removed. (note: these figures are for the presently-visible open source code and vary by Android release).

Leave the AsyncTask threads alone, please.

In addition to CommonsWare's response:

Currently I'm using Android 2.2, and my application uses no more than one AsyncTask at any time, but I'm creating a new one every x minutes. At first new AsyncTask Threads start to appear (a new Thread for a new AsyncTask) but after 5 threads (as mentioned by CommonsWare) they just stay visible in the debug window, and get re-used when new AsyncTask threads are needed. They just stay there until the debugger disconnects.

Same symptom here. In my case the threads hanged around after I'd killed the Activity, and I was hoping for the App to close completely. Problem partly solved by using a single threaded executor:

    myActiveTask.executeOnExecutor(Executors.newSingleThreadExecutor());

This made the thread to vanish after the completing its work.

Use ThreadPoolExecutor.

BlockingQueue workQueue= new LinkedBlockingQueue<Runnable>(100); // Work pool size
ThreadPoolExecutor executor = new ThreadPoolExecutor(
Runtime.getRuntime().availableProcessors(),       // Initial pool size
Runtime.getRuntime().availableProcessors(),       // Max pool size
1, // KEEP_ALIVE_TIME
TimeUnit.SECONDS, //  KEEP_ALIVE_TIME_UNIT
workQueue);

Post your Runnable task by using execute() method.

void execute (Runnable command)

Executes the given task sometime in the future. The task may execute in a new thread or in an existing pooled thread

Regarding your second query:

How can I kill these threads?

Once you are done with all your work with ThreadPoolExecutor, shutdown it properly as quoted in below post:

How to properly shutdown java ExecutorService