Android官方开发文档Training系列课程中文版:线程执行操作之定义线程执行代码

原文地址:http://android.xsoftlab.net/training/multiple-threads/index.html

引言

大量的数据处理往往需要花费很长的时间,但如果将这些工作切分并行处理,那么它的速度与效率就会提升很多。在拥有多线程处理器的设备中,系统可以使线程并行运行。比如,使用多线程将图像文件切分解码展示要比单一线程解码快得多。

这章我内容们将会学习如何设置并使用多线程及线程池。我们还会学习如何在一个线程中运行代码以及如何使该线程与UI线程进行通信。

定义在线程中运行代码

这节课我们会学习如何实现Runnable接口,该接口中的run()方法会在线程中单独执行。你也可以将Runnable对象传递给一个Thread类。这种执行特定任务的Runnable对象在某些时候被称为任务

Thread类与Runnable类同属于基础类,它们仅提供了有限的功能。它们是比如HandlerThread, AsyncTask, 以及IntentService等线程功能类的基础核心。这两个类同样属于ThreadPoolExecutor的核心基础。ThreadPoolExecutor会自动管理线程以及任务队列,它甚至还可以使多个线程同时执行。

定义Runnable实现类

实现一个Runnable对象很简单:

public class PhotoDecodeRunnable implements Runnable {
    ...
    @Override
    public void run() {
        /*
         * Code you want to run on the thread goes here
         */
        ...
    }
    ...
}

实现run()方法

Runnable的实现类中,Runnablerun()方法中所含的代码将会被执行。通常来说,Runnable中可以做任何事情。要记得,这里的Runnable不会运行在UI线程,所以在它内部不能直接修改View对象这种UI对象。如果要与UI线程通讯,你需要使用到Communicate with the UI Thread课程中所描述的技术。

run()方法的开头处设置当前的线程使用后台优先级。这种方式可以减少Runnable对象所属线程与UI线程的资源争夺问题。

这里还将Runnable对象所属的线程引用存储了起来。由Thread.currentThread()可以获得当前的线程对象。

下面是代码的具体实现方式:

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());
        ...
    }
...
}
发布了72 篇原创文章 · 获赞 126 · 访问量 64万+

猜你喜欢

转载自blog.csdn.net/u011064099/article/details/52687388