gpt4 book ai didi

Android runOnUiThread 不是异步的

转载 作者:太空狗 更新时间:2023-10-29 15:40:59 26 4
gpt4 key购买 nike

我有这段代码:

public void updateOptionLists() {
Log.d("UI", "Called update");
if (updating){
return;
}
updating = true;
runOnUiThread(
new Runnable() {
@Override
public void run() {
updating = false;
updateOptionList();
scrollToLastTapped();
Log.d("UI","Updating");
}
});
Log.d("UI", "Posted update");
}

我对 logcat 的期望是这样的:

  • 调用更新
  • 已发布更新
  • 更新

据我所知,runOnUi 应该是异步的,对吧?考虑到调用的函数会改变 View ,这需要一段时间,这应该异步运行。对吧?

所以我查看我的 logcat:

  • 调用更新
  • 更新
  • 已发布更新

为什么会这样?我如何确保它异步运行?

最佳答案

runOnUiThread 将在主线程上执行您的代码,(在此示例中)似乎也是调用它的地方。这解释了您看到的日志语句的顺序 - 所有代码都在单个线程上执行,因此是同步的 per the documentation (我的重点):

Runs the specified action on the UI thread. If the current thread is the UI thread, then the action is executed immediately. If the current thread is not the UI thread, the action is posted to the event queue of the UI thread.

runOnUiThread 通常用于在主线程上执行代码,来自 不同的线程(即后台线程)。使用这个单独的后台线程将使任务异步。如果您想使用后台线程计算的结果修改 UI,则需要在该任务结束时回调 UI 线程。

Android 提供了几种机制,用于在后台线程上执行工作,然后回发到主线程(并非所有机制都明确地使用 runOnUiThread 进行后一操作)。值得阅读的好东西包括 ThreadHandlerAsyncTaskService 等。

关于Android runOnUiThread 不是异步的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33039600/

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