Android中实现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());
...
}
...
}相关阅读:
win7自带防火墙有用吗?关闭win7系统自带的防火墙对电脑有影响吗
jquery 删除字符串最后一个字符的方法解析
jQuery实现页面滚动时动态加载内容的方法
PHP开发微信支付的代码分享
手机版win10什么样?手机版win10测试版更新详情
全面解析Bootstrap排版使用方法(文字样式)
PHP数据类型之整数类型、浮点数的介绍
js判断某个字符出现的次数的简单实例
PHP采用get获取url汉字出现乱码的解决方法
Win10预览版怎么升级至win10最新版10049?
Zend Framework教程之Application用法实例详解
简洁Ajax函数处理(示例代码)
JavaScript操作Cookie方法实例分析
Java正则表达式学习教程