如果通过 runOnUiThread 从 AsyncTask 启动,线程将保持 NEW 状态

发布于 2024-11-14 14:57:55 字数 2503 浏览 2 评论 0原文

这是我编写的一个示例应用程序,用于重现我遇到的内存泄漏相关问题:

 package a.b.mapleak;
 import android.app.Activity;
 import android.content.Context;
 import android.os.AsyncTask;
 import android.os.Bundle;
 import android.os.Handler;
 import android.util.Log;
 import android.view.View;
 import android.widget.Button;
 import android.widget.TextView;

public class MapLeak extends Activity
{
TextView callVoidText, getNewDataText, getDataStringText;
Button callVoidButton, getNewDataButton, getDataStringButton;
Handler callbackHandler;
MemoryLeak memleak;
private LoadAccountsTask mLoadAccountsTask = null;
private class LoadAccountsTask extends AsyncTask<Void, Void, Object[]> {

    private int mCursor1;
    private int mCursor2;
    private Context context;
    private UITask t = new UITask();


    @Override
    protected Object[] doInBackground(Void... params) {

        runOnUiThread(t);

        // Create the summaries cursor
        mCursor1 = 1;
        mCursor2 = 2;
        return new Object[] { mCursor1, mCursor2};
    };
  private class UITask extends Thread {
        @Override
        public void run() {
            int i = 2;
            while (i>0) {
                i--;
            }
            Thread.State state=t.getState();
            Log.e(ALARM_SERVICE, "Thread state in run is " + state.toString());

        }
    }

}


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    getDataStringText = (TextView) findViewById(R.id.getDataString_text);
    getDataStringButton = (Button) findViewById(R.id.getDataString_button);
    getDataStringButton.setOnClickListener(new Button.OnClickListener() {
        long i = 0;
        public void onClick(View v) {
           if (mLoadAccountsTask != null) mLoadAccountsTask.cancel(true);
           mLoadAccountsTask = (LoadAccountsTask) new LoadAccountsTask(this).execute();
        }
    });

}

}

我发现在 runOnUiThread 中启动的线程从未退出。由于某些我不知道的原因,任务正在运行,但

Log.e(ALARM_SERVICE, "Thread state in run is " + state.toString());

每次的输出都是“运行中的线程状态是新的”,例如“线程已创建,但从未启动。”。因此,线程不断运行,防止“LoadAccountsTask”类被垃圾收集。因此,在此示例中,每次按下按钮时,新的“LoadAccountsTask”都会出现在内存中。

但是,如果替换

private class UITask extends Thread 

private class UITask implements Run

没有内存泄漏,则线程成功退出。当然state=t.getState();在这种情况下不起作用,应该进行评论。

有人有解释为什么会这样吗?

Here is an example application I wrote to reproduce the memory leak related issue i have met :

 package a.b.mapleak;
 import android.app.Activity;
 import android.content.Context;
 import android.os.AsyncTask;
 import android.os.Bundle;
 import android.os.Handler;
 import android.util.Log;
 import android.view.View;
 import android.widget.Button;
 import android.widget.TextView;

public class MapLeak extends Activity
{
TextView callVoidText, getNewDataText, getDataStringText;
Button callVoidButton, getNewDataButton, getDataStringButton;
Handler callbackHandler;
MemoryLeak memleak;
private LoadAccountsTask mLoadAccountsTask = null;
private class LoadAccountsTask extends AsyncTask<Void, Void, Object[]> {

    private int mCursor1;
    private int mCursor2;
    private Context context;
    private UITask t = new UITask();


    @Override
    protected Object[] doInBackground(Void... params) {

        runOnUiThread(t);

        // Create the summaries cursor
        mCursor1 = 1;
        mCursor2 = 2;
        return new Object[] { mCursor1, mCursor2};
    };
  private class UITask extends Thread {
        @Override
        public void run() {
            int i = 2;
            while (i>0) {
                i--;
            }
            Thread.State state=t.getState();
            Log.e(ALARM_SERVICE, "Thread state in run is " + state.toString());

        }
    }

}


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    getDataStringText = (TextView) findViewById(R.id.getDataString_text);
    getDataStringButton = (Button) findViewById(R.id.getDataString_button);
    getDataStringButton.setOnClickListener(new Button.OnClickListener() {
        long i = 0;
        public void onClick(View v) {
           if (mLoadAccountsTask != null) mLoadAccountsTask.cancel(true);
           mLoadAccountsTask = (LoadAccountsTask) new LoadAccountsTask(this).execute();
        }
    });

}

}

I found that the thread started in runOnUiThread has never been exited. For some unknown to me reason the task was running, but the output from

Log.e(ALARM_SERVICE, "Thread state in run is " + state.toString());

every time was "Thread state in run is NEW" e.g. ''The thread has been created, but has never been started.''. So the thread was running continuously preventing "LoadAccountsTask" class from being garbage collected. Thus, in this example, every time the button is pressed - the new "LoadAccountsTask" appeared in memory.

But, if to replace

private class UITask extends Thread 

with

private class UITask implements Run

there was no memory leak, the thread exited successfully. Of course state=t.getState(); will not work in this case and should be commented.

Do anybody have an explanation why it is so?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

猫性小仙女 2024-11-21 14:57:55

关注您眼前的问题,runOnUiThread() 采用 Runnable。虽然 Thread 确实实现了 Runnable,但 runOnUiThread() 不会将其视为 Thread。请仅将 Runnable 传递给 runOnUiThread()

其次,切勿从 doInBackground() 调用 runOnUiThread()。只需在 onPreExecute()onPostExecute() 中执行该 Runnable 的工作即可,这些工作在主应用程序线程上执行。

第三,如果您确实编写了一个真正的Thread,请不要在其中忙循环。

Focusing on your immediate concern, runOnUiThread() takes a Runnable. While Thread does implement Runnable, runOnUiThread() will not treat it as a Thread. Please just pass a Runnable to runOnUiThread().

Second, never call runOnUiThread() from doInBackground(). Just perform the work from that Runnable in onPreExecute() or onPostExecute(), which are executed on the main application thread.

Third, if you ever do write a real Thread, don't busy-loop in it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文