Android 线程池系列教程(2)Thread,Runnable是基类及如何写Run方法
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:
1 public class PhotoDecodeRunnable implements Runnable { 2 ... 3 @Override 4 public void run() { 5 /* 6 * Code you want to run on the thread goes here 7 */ 8 ... 9 } 10 ... 11 }
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:
1 class PhotoDecodeRunnable implements Runnable { 2 ... 3 /* 4 * Defines the code to run for this task. 5 */ 6 @Override 7 public void run() { 8 // Moves the current Thread into the background 9 android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND); 10 ... 11 /* 12 * Stores the current Thread in the PhotoTask instance, 13 * so that the instance 14 * can interrupt the Thread. 15 */ 16 mPhotoTask.setImageDecodeThread(Thread.currentThread()); 17 ... 18 } 19 ... 20 }