Android(安卓)Developers:指定在线程中运行的代码
这个课程向你展示如何实现一个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()); ... } ... }
更多相关文章
- Android中的动态加载机制
- Android通过scroller实现缓慢移动
- Android(安卓)Frame动画概述及示例
- Android(安卓)Studio---断点调试和高级调试
- UISwipeGestureRecognizer ---手指动作
- 从使用到源码,细说 Android(安卓)中的 tint 着色器
- Android(安卓)反射机制
- Cursor与Adapter结合使用
- Android(安卓)UI开发——使用Fragment构建灵活的桌面