Android中实现Runnable接口简单例子
16lz
2021-01-26
本课讲的是如何实现一个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());
...
}
...
}
更多相关文章
- SpringBoot 2.0 中 HikariCP 数据库连接池原理解析
- Android系列之Intent传递对象的几种实例方法
- 探秘ListView的ConvertView以及ViewHolder原理
- Android引入第三方jar包的方法
- [android] Proguard代码混淆器如何排除指定的类或子类
- Android(安卓)网络连接:HttpUtils 的GET、POST与注解
- Android——ContentProvider总结
- Android中使用定时器的三种方法
- Support Annotation Library使用详解