这个课程向你展示如何实现一个Runnalbe类,它在一个单独的线程中运行它的Runnable.run()方法中的代码。你也能传递一个Runnable给其它的对象,然后将它连接到一个线程并且运行它。一个或者多个执行一个特殊操作的Runnable对象在某些时候被称之为一个任务。

Thread和Runnabl都是基础类,凭借它们自己,只有有限的能力。相反,它们是强大的Android类的基础,如HandlerThread,AsyncTask,和IntentService.Thread和Runnable也是ThreadPollExecutor类的基础。这节类自动管理线程和任务队列,也可以并行运行多个线程。

定义一个实现Runnable的类

————————————————————————————————————————————————————————————————

实现一个实现了Runnalbe的类是简单的。例如

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线程对象,如View对象。为了和UI线程通信,你必须使用在Communicate with the UIThread课程中被描述的技术

在run()方法的开始,通过使用THREAD_PRIORITY_BACKGROUND调用Process.setThreadPriority()方法来设置线程使用的后台优先级。这个方式降低了在Runnable对象的线程和UI线程之间的资源竞争

你也应该在这个Runnable自己中保存一个Runnable对象的线程的引用,通过调用Thead.currentThread()方法

下面的代码片段展示了如何设置这个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 the PhotoTask instance,          * so that the instance          * can interrupt the Thread.          */         mPhotoTask.setImageDecodeThread(Thread.currentThread());         ...     } ... } 

更多相关文章

  1. Android中的动态加载机制
  2. Android通过scroller实现缓慢移动
  3. Android(安卓)Frame动画概述及示例
  4. Android(安卓)Studio---断点调试和高级调试
  5. UISwipeGestureRecognizer ---手指动作
  6. 从使用到源码,细说 Android(安卓)中的 tint 着色器
  7. Android(安卓)反射机制
  8. Cursor与Adapter结合使用
  9. Android(安卓)UI开发——使用Fragment构建灵活的桌面

随机推荐

  1. mysql 中 replace into 与 insert into o
  2. 解决MySQL server has gone away错误的方
  3. centos7环境下创建mysql5.6多实例的方法
  4. centos7环境下二进制安装包安装 mysql5.6
  5. 分享MySql8.0.19 安装采坑记录
  6. centos7环境下源码安装mysql5.7.16的方法
  7. mysql非主键自增长用法实例分析
  8. win10安装zip版MySQL8.0.19的教程详解
  9. mysql中GROUP_CONCAT的使用方法实例分析
  10. Window下如何恢复被删除的Mysql8.0.17 Ro