1.This lesson teaches you to
2.You should also read
3.Try it out
ThreadSample.zip
This lesson 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 moreRunnable
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
, andIntentService
. 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.
4.Define a Class that Implements Runnable
Implementing 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
*/
...
}
...
}
5.Implement the run() Method
In the class, the Runnable.run()
method contains the code that's executed. Usually, anything is allowable in aRunnable
. 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 callingProcess.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 callingThread.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());
...
}
...
}