有没有一种健壮的方法来检测Thread.currentThread()
是否是应用程序中的安卓系统UI线程?
我想在我的模型代码中添加一些断言,断言只有一个线程(例如UI线程)访问我的状态,以确保不需要任何类型的同步。
发布于 2011-10-26 08:50:36
确定UI线程身份的常见做法是通过Looper#getMainLooper
if (Looper.getMainLooper().getThread() == Thread.currentThread()) {
// On UI thread.
} else {
// Not on UI thread.
}
从API23级开始,在主循环中使用新的帮助器方法isCurrentThread,可读性更好一些:
if (Looper.getMainLooper().isCurrentThread()) {
// On UI thread.
} else {
// Not on UI thread.
}
发布于 2012-04-07 03:56:31
我认为最好的方法是:
if (Looper.getMainLooper().equals(Looper.myLooper())) {
// UI thread
} else {
// Non UI thread
}
发布于 2018-02-12 21:01:33
在API23级,Looper
有一个很好的助手方法isCurrentThread
。您可以通过这种方式获取mainLooper
并查看它是否是当前线程的way:
Looper.getMainLooper().isCurrentThread()
它实际上与以下内容相同:
Looper.getMainLooper().getThread() == Thread.currentThread()
但它的可读性可能更好一些,更容易记忆。
https://stackoverflow.com/questions/2848575
复制相似问题