<最近在学习多线程的知识>
这篇文章文章展示了如何实现一个Runnable类,在独立线程中该类在它的Runnable.run()方法中运行代码。你也可以传递一个Runnable到另外一个对象,可以把它加载到一个线程上然后运行。一个或多个Runnable对象完成一个特殊的操作有时被称为一个线程。
Thread和Runnable就他们本身而言是基本的类,只有有限的能力。相反,他们有强大的Android类作为基础,这些类如HandlerThread,AsyncTask,和IntentService。Thread和Runnable也是ThreadPoolExecutor类的基础。该类自动管理线程和任务队列,甚至可以同时运行多个线程。
定义一个类实现Runnable
完成一个实现Runnable接口的类很简单,如示例:
public class PhotoDecodeRunnable implements Runnable {
...
@Override
public void run() {
/*
* Code you want to run on the thread goes here
*/
...
}
...
}
完成run()方法
在这个类中,Runnable.run()方法包含要执行的代码。通常说,任何代码都可以放在Runnable中。记住,因为Runnable不可以在主线程中运行,所以它不可以直接修改UI对象例如View对象。为了实现与主线程通信,你必须使用Communication with the UI Thread一章中描述的技巧。
在run()方法的开始,通过调用Process.setThreadPriority()来设置线程的优先级为THREAD_PRIORITY_BACKGROUND。这种方式减少了Runnable对象线程与主线程之间的资源竞争。
通过调用Thread.currentThread()方法,你还应该保存Runnable对象线程的一个引用在Runnable里面。
下面的一段展示了如何建立一个run()方法:
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());
...
}
...
}