在后台线程中启动可运行对象

18

据我所知,我已经实现了一个在新线程上创建的可运行程序。然而,这个线程似乎没有在后台运行,而在可运行程序内部执行的操作会因为过重而导致用户界面停滞。

请参见下面:

custListLoadThread = new Thread(loadRunnable);
custListLoadThread.run();

private Runnable loadRunnable = new Runnable()
{
    @Override
    public void run()
    {
        android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);

        Gen.popup("TEST"); // Creates a toast pop-up.
        // This is to know if this runnable is running on UI thread or not!

        try
        {               
            customers = Db.BasicArrays.getCustomers(CustomApp.Session.businessCode, empId);

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    populate();
                    setCustListVisible(true);
                    loading = false;
                }
            });
        }
        catch (final Exception ex)
        {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Gen.popup(ex.getMessage());
                }
            });
        }
    }
};

然而,这段代码并没有在后台运行,仍然似乎在UI线程上运行。我添加了Gen.popup("TEST");用于确认此情况(在非UI线程中调用toast弹出应该会引发错误)。

有任何想法,为何这个可运行程序没有在后台运行?

2个回答

30
custListLoadThread = new Thread(loadRunnable);
custListLoadThread.start();

你需要启动线程,而不是在当前线程中调用run()方法。


那就是问题所在,非常感谢!被 runstart 的相似性给搞混了! - Mike Baxter

16

如果您想在后台线程上执行代码而不涉及UI:

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            //your action
        }
    };
    AsyncTask.execute(runnable);

当然,正如之前所述,您也可以创建一个新线程(独立于UI线程):

    new Thread(runnable).start();

在您的示例中,您希望更新UI元素,因此最好使用AsyncTask(必须从UI线程调用!):

    new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... params) {
            // your async action
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            // update the UI (this is executed on UI thread)
            super.onPostExecute(aVoid);
        }
    }.execute();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接