我在堆栈上读到了这个:
When you use new Handler().post(r) (or Message), you added the Runnable object to Looper and execute the code later in the same thread.
此答案已被接受。
所以现在我陷入了困境,我上次采访中的一些人给了我提示:如果你想在其他线程中运行某些东西并从这个新线程 UI 进行更新,让我们使用处理程序。
那么 Handler 是否是新线程?
或者也许可以在这个线程中运行在其他线程上工作?
有人能给我解释一下吗?
来自官方文档:
There are two main uses for a Handler: (1) to schedule messages and runnables to be executed at some point in the future; and (2) to enqueue an action to be performed on a different thread than your own.
最佳答案
Handler
不是一个新线程。它只是一种安排在 UI 线程中完成某些任务的机制。- 创建/发布到
处理程序
不会创建新线程。 - 一旦 UI 线程空闲,发布到
Handler
的Runnable
就会在 UI 线程中运行。
当您创建一个 Runnable
实例并发布它时,它的引用将被存储,并且它的 run
方法将在将来的某个时刻从 UI 线程调用。 (您还可以使用 postDelayed()
方法指定延迟。)
关于java - 处理程序和接口(interface)可运行 - 有新线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52475338/