在后台线程中启动runnable

时间:2014-07-18 11:19:22

标签: android multithreading 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());
                }
            });
        }
    }
};

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

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

2 个答案:

答案 0 :(得分:23)

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

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

答案 1 :(得分:11)

如果要在后台线程上执行代码,该代码不对UI执行任何操作:

curl -L -H 'Content-Type: application/json' -X POST chronos-node:8080/scheduler/iso8601 -d '
{
  "schedule": "R/2016-04-15T12:00:00Z/PT2M",
  "name": "spark-submit-job",
  "container": {
    "type": "DOCKER",
    "image": "my/sparksubmitapp",
    "network": "BRIDGE",
    "forcePullImage": true
  },
  "cpus": "0.5",
  "mem": "1024",
  "uris": [],
  "command": "/path/to/spark/bin/spark-submit --class com.my.app.Main myApp.jar"
}'

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

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

在您的示例中,您想要更新UI元素,因此最好使用 new Thread(runnable).start(); (必须从UI线程调用!):

AsyncTask