问题描述
Handler、Runnable 和 Threads 有什么区别?
What is the difference between Handler, Runnable, and Threads?
当我使用 android 时,我需要一些东西在后台运行.我使用线程来运行它.通常我会写一个类来扩展Thread并实现run方法.
While I was working with android, and I need something to run in the background. I use Threads to run it. Usually I would write a class that extends Thread and implement the run method.
我还看到了一些实现 runnable 并将 runnable 传递给线程的示例.
I have also saw some examples that implments runnable and pass into runnable into Threads.
但是我还是很困惑.谁能给我一个清楚的解释?
However I am still confused. Can someone give me a clear explanation?
- 如果可以在 Thread 的 run 方法中编写后台代码,那么 Runnable 的意义何在?
- Handler 在线程内部是如何使用的,为什么我们需要使用它.
- Android 还有一个东西叫 runOnUiThread,我们如何使用它?我知道它用于更新 UI.
推荐答案
为什么使用 Runnable over Thread?
Runnable
将需要异步运行的代码与如何运行代码分开.这使您的代码保持灵活.例如,可运行对象中的异步代码可以在线程池或专用线程上运行.
Runnable
separates code that needs to run asynchronously, from how the code is run. This keeps your code flexible. For instance, asynchronous code in a runnable can run on a threadpool, or a dedicated thread.
一个 Thread
有状态你的 runnable 可能不需要访问.访问比必要更多的状态是糟糕的设计.
A Thread
has state your runnable probably doesn't need access to. Having access to more state than necessary is poor design.
线程占用大量内存.为每个小动作创建一个新线程需要处理时间来分配和释放此内存.
Threads occupy a lot of memory. Creating a new thread for every small actions takes processing time to allocate and deallocate this memory.
runOnUiThread 实际上在做什么?
Android 的 runOnUiThread 排队
Runnable
在 UI 线程上执行.这很重要,因为您永远不应该从多个线程更新 UI.runOnUiThread
使用一个Handler
.
Android's runOnUiThread queues a
Runnable
to execute on the UI thread. This is important because you should never update UI from multiple threads.runOnUiThread
uses aHandler
.
请注意,如果 UI 线程的队列已满,或者需要执行的项目很长,则排队的 Runnable
可能需要一段时间才能真正运行.
Be aware if the UI thread's queue is full, or the items needing execution are lengthy, it may be some time before your queued Runnable
actually runs.
什么是处理程序?
- 处理程序允许您发布可运行对象以在特定线程上执行.在幕后,runOnUi Thread 将您的
Runnable
与 Android 的 Ui 处理程序一起排队,以便您的 runnable 可以在 UI 线程上安全地执行.
- A handler allows you to post runnables to execute on a specific thread. Behind the scenes, runOnUi Thread queues your
Runnable
up with Android's Ui Handler so your runnable can execute safely on the UI thread.
这篇关于Handler、Runnable 和 Threads 之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!