Starting a runnable in background thread

Mike Baxter picture Mike Baxter · Jul 18, 2014 · Viewed 28k times · Source

I have, to my knowledge, implemented a runnable which is created on a new thread. However, the thread does not seem to be running in the background, and the actions taken inside the runnable are stalling the UI with heavy actions.

See below:

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());
                }
            });
        }
    }
};

However this code does not run in the background, it still seems to run on the UI thread. I have placed the line Gen.popup("TEST"); to make sure of this (calling a toast pop up in a non-UI thread should cause an error).

Any ideas as to why this runnable isn't running in the background?

Answer

Steve M picture Steve M · Jul 18, 2014
custListLoadThread = new Thread(loadRunnable);
custListLoadThread.start();

You need to start the thread, not call the run() method in the current thread.