【发布时间】:2011-02-20 08:55:40
【问题描述】:
是否有可靠的方法来检测 Thread.currentThread() 是否是应用程序中的 Android 系统 UI 线程?
我想在我的模型代码中添加一些断言,断言只有一个线程(例如 ui 线程)访问我的状态,以确保不需要任何同步。
【问题讨论】:
-
在这里查看我的答案:stackoverflow.com/a/41280460/878126
标签: android
是否有可靠的方法来检测 Thread.currentThread() 是否是应用程序中的 Android 系统 UI 线程?
我想在我的模型代码中添加一些断言,断言只有一个线程(例如 ui 线程)访问我的状态,以确保不需要任何同步。
【问题讨论】:
标签: android
确定 UI 线程身份的常用做法是通过Looper#getMainLooper:
if (Looper.getMainLooper().getThread() == Thread.currentThread()) {
// On UI thread.
} else {
// Not on UI thread.
}
从 API 级别 23 起,在主循环器上使用新的辅助方法 isCurrentThread 有一种更易读的方法:
if (Looper.getMainLooper().isCurrentThread()) {
// On UI thread.
} else {
// Not on UI thread.
}
【讨论】:
我认为最好的方法是:
if (Looper.getMainLooper().equals(Looper.myLooper())) {
// UI thread
} else {
// Non UI thread
}
【讨论】:
equals,因为我们只是比较引用,最重要的是,它们都是静态的。
从 API 级别 23 开始,Looper 有一个很好的辅助方法 isCurrentThread。您可以通过这种方式获取mainLooper 并查看它是否是当前线程的那个:
Looper.getMainLooper().isCurrentThread()
实际上是一样的:
Looper.getMainLooper().getThread() == Thread.currentThread()
但它可能更易读,更容易记住。
【讨论】:
public boolean onUIThread() {
return @987654321@.@987654322@.@987654323@;
}
但它需要 API 级别 23
【讨论】:
除了检查looper,如果你曾尝试注销onCreate()中的线程ID,你可以找到UI线程(主线程) id 总是等于 1。因此
if (Thread.currentThread().getId() == 1) {
// UI thread
}
else {
// other thread
}
【讨论】:
Kotlin 的不错的扩展:
val Thread.isMain get() = Looper.getMainLooper().thread == Thread.currentThread()
所以你只需调用:
Thread.currentThread().isMain
【讨论】:
您不能在Activity 类中使用runOnUiThread 方法吗?见..
【讨论】: