The speed and efficiency of a long-running, data-intensive operation often improves when you split it into smaller operations running on multiple threads. On a device that has a CPU with multiple processors (cores), the system can run the threads in parallel, rather than making each sub-operation wait for a chance to run. For example, decoding multiple image files in order to display them on a thumbnail screen runs substantially faster when you do each decode on a separate thread.
当你将一个需要长时间运行的,聚焦于数据的操作,分割成一些小的操作,并且在多线程中运行的话,那么这个长时间运行的操作的速度和效率将会提升不少。对于一个有多核的设备,系统可以并发的运行多个线程,而不是让每个子操作等到被执行。比如,当你要解码多张图片,以在屏幕上显示的话,你如果将每一个图片的解码操作放在每一个独立的线程的话,那么速度将会很快。
This class shows you how to set up and use multiple threads in an Android app, using a thread pool object. You'll also learn how to define code to run on a thread and how to communicate between one of these threads and the UI thread.
本课程将会向你展示,如何通过一个线程池对象,来创立和使用多线程。你同样也会学到如何使得代码在线程中宇星,以及这些线程如何与主线程通信。
Lessons
- Specifying the Code to Run on a Thread
- Learn how to write code to run on a separate
Thread
, by defining a class that implements theRunnable
interface. - Creating a Manager for Multiple Threads
- Learn how to create an object that manages a pool of
Thread
objects and a queue ofRunnable
objects. This object is called aThreadPoolExecutor
. - Running Code on a Thread Pool Thread
- Learn how to run a
Runnable
on a thread from the thread pool. - Communicating with the UI Thread
- Learn how to communicate from a thread in the thread pool to the UI thread.
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步