在后台线程中启动runnable

Mik*_*ter 14 multithreading android runnable

据我所知,我已经实现了一个在新线程上创建的runnable.但是,该线程似乎并未在后台运行,并且在runnable中执行的操作正在使用大量操作阻止UI.

见下文:

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());
                }
            });
        }
    }
};
Run Code Online (Sandbox Code Playgroud)

但是这段代码不能在后台运行,它似乎仍然在UI线程上运行.我已经放置了这一行Gen.popup("TEST");以确保这一点(toast在非UI线程中调用弹出应该会导致错误).

关于为什么这个runnable没有在后台运行的任何想法?

Ste*_*e M 24

custListLoadThread = new Thread(loadRunnable);
custListLoadThread.start();
Run Code Online (Sandbox Code Playgroud)

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


Tim*_*ähr 12

如果要在不对UI执行某些操作的后台线程上执行代码:

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

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

    new Thread(runnable).start();
Run Code Online (Sandbox Code Playgroud)

在您的示例中,您想要更新UI元素,因此最好使用a 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();
Run Code Online (Sandbox Code Playgroud)