Android 线程池系列教程(2)Thread,Runnable是基类及如何写Run方法
1.This lesson teaches you to
2.You should also read
3.Try it out
ThreadSample.zip
This lesson shows you how to implement a Runnable
class, which runs the code in its Runnable.run()
method on a separate thread. You can also pass a Runnable
to another object that can then attach it to a thread and run it. One or moreRunnable
objects that perform a particular operation are sometimes called a task.
Thread
and Runnable
are basic classes that, on their own, have only limited power. Instead, they're the basis of powerful Android classes such as HandlerThread
, AsyncTask
, andIntentService
. Thread
and Runnable
are also the basis of the class ThreadPoolExecutor
. This class automatically manages threads and task queues, and can even run multiple threads in parallel.
4.Define a Class that Implements Runnable
Implementing a class that implements Runnable
is straightforward. For example:
1 public class PhotoDecodeRunnable implements Runnable { 2 ... 3 @Override 4 public void run() { 5 /* 6 * Code you want to run on the thread goes here 7 */ 8 ... 9 } 10 ... 11 }
5.Implement the run() Method
In the class, the Runnable.run()
method contains the code that's executed. Usually, anything is allowable in aRunnable
. Remember, though, that the Runnable
won't be running on the UI thread, so it can't directly modify UI objects such as View
objects. To communicate with the UI thread, you have to use the techniques described in the lesson Communicate with the UI Thread.
At the beginning of the run()
method, set the thread to use background priority by callingProcess.setThreadPriority()
with THREAD_PRIORITY_BACKGROUND
. This approach reduces resource competition between the Runnable
object's thread and the UI thread.
You should also store a reference to the Runnable
object's Thread
in the Runnable
itself, by callingThread.currentThread()
.
The following snippet shows how to set up the run()
method:
1 class PhotoDecodeRunnable implements Runnable { 2 ... 3 /* 4 * Defines the code to run for this task. 5 */ 6 @Override 7 public void run() { 8 // Moves the current Thread into the background 9 android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND); 10 ... 11 /* 12 * Stores the current Thread in the PhotoTask instance, 13 * so that the instance 14 * can interrupt the Thread. 15 */ 16 mPhotoTask.setImageDecodeThread(Thread.currentThread()); 17 ... 18 } 19 ... 20 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 【杂谈】分布式事务——高大上的无用知识?