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()); 
        ... 
    } 
... 
} 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值