gpt4 book ai didi

java - Runnable 运行在哪个线程上?

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:35:08 24 4
gpt4 key购买 nike

我想每 100 毫秒更新一次 UI。在 StackOverflow 中搜索后,我找到了一个使用 RunnableHandler 的解决方案,如下所示

final Handler handler = new Handler();
Runnable runnable = new Runnable() {
@Override
public void run() {
//update UI here

handler.postDelayed(this, 100);
}
};
runnable.run();

有效!但我有一些问题:

  1. 这个 Runnable 在哪个线程上运行? MainThread 还是另一个线程?这是关于 postDelay 的文档 enter image description here

Handler 附加在 MainThread 上,那么 Runnable 是否在 MainThread 上运行?

  1. 如果 Runnable 运行在 MainThread 上,为什么需要 Handler?据我所知,Handler是用来在两个线程之间发送消息的

最佳答案

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() 只是一个方法调用。

无论 Handler 在哪个线程中运行,Handler 对该线程的后续 执行,除了重新安排它们自己之外基本上什么都不做。很难相信这是解决任何问题的方法。

关于java - Runnable 运行在哪个线程上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47670169/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com