多线程发送操作之一:运行一个线程的格式化代码(Specifying the Code to Run on a Thread)

<最近在学习多线程的知识>

这篇文章文章展示了如何实现一个Runnable类,在独立线程中该类在它的Runnable.run()方法中运行代码。你也可以传递一个Runnable到另外一个对象,可以把它加载到一个线程上然后运行。一个或多个Runnable对象完成一个特殊的操作有时被称为一个线程。

Thread和Runnable就他们本身而言是基本的类,只有有限的能力。相反,他们有强大的Android类作为基础,这些类如HandlerThread,AsyncTask,和IntentService。Thread和Runnable也是ThreadPoolExecutor类的基础。该类自动管理线程和任务队列,甚至可以同时运行多个线程。

定义一个类实现Runnable

完成一个实现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对象例如View对象。为了实现与主线程通信,你必须使用Communication with the UI Thread一章中描述的技巧。

在run()方法的开始,通过调用Process.setThreadPriority()来设置线程的优先级为THREAD_PRIORITY_BACKGROUND。这种方式减少了Runnable对象线程与主线程之间的资源竞争。

通过调用Thread.currentThread()方法,你还应该保存Runnable对象线程的一个引用在Runnable里面。

下面的一段展示了如何建立一个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 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、付费专栏及课程。

余额充值