Runnable在哪个线程上运行? [英] Which thread does Runnable run on?
问题描述
我想每100毫秒更新一次UI.在StackOverflow中搜索之后,我找到了使用Runnable
和Handler
这样的解决方案
I want to update UI every 100ms. After searching in StackOverflow, I found a solution using Runnable
and Handler
like this
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
@Override
public void run() {
//update UI here
handler.postDelayed(this, 100);
}
};
runnable.run();
有效!但是我有一些问题:
It works! But I have some questions:
- 此
Runnable
在哪个线程上运行? MainThread还是另一个线程?这是有关postDelay
的文档
- Which thread does this
Runnable
run on? MainThread or another thread? Here is the docs aboutpostDelay
Handler
已附加MainThread,所以Runnable
是否在MainThread上运行?
Handler
is attached MainThread, so is Runnable
running on MainThread?
- 如果
Runnable
在MainThread上运行,为什么需要Handler
?据我了解,Handler
用于在两个线程之间发送消息
- If
Runnable
is running on MainThread, why needsHandler
? According to my knowledge,Handler
is used to send messages between two threads
推荐答案
该Runnable在哪个线程上运行?
Which thread does this Runnable run on?
Runnable runnable = new Runnable() {
@Override
public void run() {
//update UI here
handler.postDelayed(this, 100);
}
};
runnable.run()
此Runnable
在当前线程(即调用此代码的线程)上运行.它不会神奇地创建或构成另一个线程. Runnable.run()
仅仅是方法调用.
This Runnable
runs on the current thread, i.e. the thread that invokes this code. It doesn't magically create, or constitute, another thread. Runnable.run()
is only a method call.
在Handler
所运行的任何线程中,Handler
对该线程的后续执行,除了重新安排自身之外,基本上不执行任何操作.很难相信这可以解决任何问题.
The subsequent executions of this thread, by the Handler
, in whatever thread the Handler
runs in, do essentially nothing except reschedule themselves. It's hard to believe this is a solution to anything.
这篇关于Runnable在哪个线程上运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!