Skip to content

Latest commit

 

History

History
109 lines (87 loc) · 3.76 KB

将操作发送到多个线程——(2)指定线程中运行的代码.md

File metadata and controls

109 lines (87 loc) · 3.76 KB

将操作发送到多个线程——指定线程中运行的代码

原文(英文)地址

本文介绍如何实现Runnable类,该类在单独的线程上运行其Runnable.run()方法中的代码。您还可以将Runnable传递给另一个对象,然后将该对象附加到线程中并运行它。执行特定操作的一个或多个Runnable对象有时称为任务。

ThreadRunnable都是基类,它们本身只有有限的功能。但是,它们是很多强大的Android类的基类,例如HandlerThreadAsyncTaskIntentServiceThreadRunnable也是ThreadPoolExecutor类的基类。该类自动管理线程和任务队列,甚至可以并行运行多个线程。

定义实现Runnable的类

定义一个类并实现Runnable接口很简单,比如:

  • kotlin

  • class PhotoDecodeRunnable : Runnable {
        ...
        override fun run() {
            /*
             * Code you want to run on the thread goes here
             */
            ...
        }
        ...
    }
  • java

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

实现run()方法

在实现了Runnable接口的类中,Runnable.run()方法包含要在子线程执行的代码。通常,Runnable中允许执行任何内容。但请记住,Runnable不会在UI线程上运行,因此它无法直接更新UI(如更新View)。要与UI线程通信,您必须使用与UI线程通信中描述的技术。

run()方法的开头,通过调用Process.setThreadPriority()并传入使用THREAD_PRIORITY_BACKGROUND,设置线程可以使用后台优先级。这种方法减少了Runnable对象的线程和UI线程之间的资源竞争。

您还应该通过调用Thread.currentThread()Runnable中存储对Runnable对象对应的Thread的引用。

以下代码段显示了如何设置run()方法:

  • kotlin

  • class PhotoDecodeRunnable : Runnable {
    ...
        /*
         * Defines the code to run for this task.
         */
        override fun 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.
             */
            photoTask.setImageDecodeThread(Thread.currentThread())
            ...
        }
    ...
    }
  • java

  • 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.
             */
            photoTask.setImageDecodeThread(Thread.currentThread());
            ...
        }
    ...
    }

更多内容

关于Android中多线程的更多内容,请参阅进程和线程——概述

示例app

ThreadSample