【后台任务】指定要在线程上运行的代码(4)

概要


本指南向您介绍如何实现一个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不会在UI线程上运行,因此它不能直接修改UI对象(如View对象)。要与UI线程进行通信,您必须使用本课中描述的技术 与UI线程通信。

在年初run()的方法,设置线程调用使用后台优先 Process.setThreadPriority()使用 THREAD_PRIORITY_BACKGROUND。这种方法减少了Runnable对象线程和UI线程之间的资源竞争。

你也应该存储到一个参考Runnable对象 Thread在Runnable调用本身 Thread.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 PhotoTask instance,
         * so that the instance
         * can interrupt the Thread.
         */
        mPhotoTask.setImageDecodeThread(Thread.currentThread());
        ...
    }
...
}

更多信息


要了解更多关于Android上的多线程操作的信息,请参阅过程和线程概述指南。

示例应用


要尝试本指南中的概念,请下载ThreadSample

Lastest Update:2018.04.17

联系我

QQ:94297366
微信打赏:https://pan.baidu.com/s/1dSBXk3eFZu3mAMkw3xu9KQ

扫描二维码关注公众号,回复: 1448858 查看本文章

公众号推荐:

【后台任务】指定要在线程上运行的代码(4)

猜你喜欢

转载自blog.51cto.com/4789781/2124454