Android中实现Runnable接口简单例子
Android中实现Runnable接口简单例子
发布时间:2016-12-28 来源:查字典编辑
摘要:本课讲的是如何实现一个Runnable,在一个独立线程上运行Runnable.run()方法.Runnable对象执行特别操作有时叫作任务。...

本课讲的是如何实现一个Runnable,在一个独立线程上运行Runnable.run()方法.Runnable对象执行特别操作有时叫作任务。

Thread和Runnable都是基础的类,靠他们自己,能力有限。作为替代,Android有强大的基础类,像HandlerThread,AsyncTask,IntentService。Thread和Runnable也是ThreadPoolExecutor的基础类。这个类可以自动管理线程和任务队列,甚至可以并行执行多线程。

定义一个实现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运行,所以不能直接修改UI对象属性。与UI通讯,参考Communicate with the UI Thread

在run()方法的开始,调用 android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);设置线程的权重,android.os.Process.THREAD_PRIORITY_BACKGROUND比默认的权重要低,所以资源会优先分配给其他线程(UI线程)

你应该保存线程对象的引用,通过调用 Thread.currentThread()

复制代码 代码如下:

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

...

}

...

}

推荐文章
猜你喜欢
附近的人在看
推荐阅读
拓展阅读
相关阅读
网友关注
最新安卓软件开发学习
热门安卓软件开发学习
编程开发子分类