本文介绍如何实现Runnable类,该类在单独的线程上运行其Runnable.run()方法中的代码。您还可以将Runnable
传递给另一个对象,然后将该对象附加到线程中并运行它。执行特定操作的一个或多个Runnable
对象有时称为任务。
Thread
和Runnable
都是基类,它们本身只有有限的功能。但是,它们是很多强大的Android
类的基类,例如HandlerThread
,AsyncTask
和IntentService
。 Thread
和Runnable
也是ThreadPoolExecutor
类的基类。该类自动管理线程和任务队列,甚至可以并行运行多个线程。
定义一个类并实现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 */ ... } ... }
在实现了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中多线程的更多内容,请参阅进程和线程——概述