Specify the code to run on a thread

This guide shows you how to implement a Runnable class, which runs the code in its Runnable.run() method on a separate thread. You can also pass a Runnable to another object that can then attach it to a thread and run it. One or more Runnable objects that perform a particular operation are sometimes called a task.

Thread and Runnable are basic classes that, on their own, have only limited power. Instead, they're the basis of powerful Android classes such as HandlerThread, AsyncTask, and IntentService. Thread and Runnable are also the basis of the class ThreadPoolExecutor. This class automatically manages threads and task queues, and can even run multiple threads in parallel.

Define a class that implements Runnable

Creating a class that implements Runnable is straightforward. For example:

public class PhotoDecodeRunnable implements Runnable {
    ...
    @Override
    public void run() {
        /*
         * Code you want to run on the thread goes here
         */
        ...
    }
    ...
}

Implement the run() method

In the class, the Runnable.run() method contains the code that's executed. Usually, anything is allowable in a Runnable. Remember, though, that the Runnable won't be running on the UI thread, so it can't directly modify UI objects such as View objects. To communicate with the UI thread, you have to use the techniques described in the lesson Communicate with the UI thread.

At the beginning of the run() method, set the thread to use background priority by calling Process.setThreadPriority() with THREAD_PRIORITY_BACKGROUND. This approach reduces resource competition between the Runnable object's thread and the UI thread.

You should also store a reference to the Runnable object's Thread in the Runnable itself, by calling Thread.currentThread().

The following snippet shows how to set up the run() method:

class PhotoDecodeRunnable implements Runnable {
...
    /*
     * Defines the code to run for this task.
     */
    @Override
    public void run() {
        // Moves the current Thread into the background
        android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);
        ...
        /*
         * Stores the current Thread in the PhotoTask instance,
         * so that the instance
         * can interrupt the Thread.
         */
        mPhotoTask.setImageDecodeThread(Thread.currentThread());
        ...
    }
...
}

More information

To learn more about multi-threaded operations on Android, see the Process and threads overview guide.

Sample app

To try out the concepts in this guide, download ThreadSample.