源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

Android中实现Runnable接口简单例子

  • 时间:2020-07-10 02:46 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:Android中实现Runnable接口简单例子
本课讲的是如何实现一个Runnable,在一个独立线程上运行Runnable.run()方法.Runnable对象执行特别操作有时叫作任务。 Thread和Runnable都是基础的类,靠他们自己,能力有限。作为替代,Android有强大的基础类,像HandlerThread,AsyncTask,IntentService。Thread和Runnable也是ThreadPoolExecutor的基础类。这个类可以自动管理线程和任务队列,甚至可以并行执行多线程。 [b]定义一个实现Runnable接口的类[/b]
[u]复制代码[/u] 代码如下:
public class PhotoDecodeRunnable implements Runnable {     ...     @Override     public void run() {         /*          * Code you want to run on the thread goes here          */         ...     }     ... }
[b]实现run()方法[/b] 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()
[u]复制代码[/u] 代码如下:
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());         ...     } ... }
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部