如何检查当前线程是否不是主线程

本文翻译自:How to check if current thread is not main thread

I need to check if the thread running a certain piece of code is the main (UI) thread or not. 我需要检查运行某段代码的线程是否是主(UI)线程。 How can I achieve this? 我怎样才能做到这一点?


#1楼

参考:https://stackoom.com/question/lsWk/如何检查当前线程是否不是主线程


#2楼

Looper.myLooper() == Looper.getMainLooper()

如果这返回true,那么你就是UI线程!


#3楼

you can use below code to know if current thread is UI/Main thread or not 您可以使用下面的代码来了解当前线程是否是UI /主线程

if(Looper.myLooper() == Looper.getMainLooper()) {
   // Current Thread is Main Thread.
}

or you can also use this 或者你也可以使用它

if(Looper.getMainLooper().getThread() == Thread.currentThread()) {
   // Current Thread is Main Thread.
}

Here is similar question 这是类似的问题


#4楼

你可以在android ddms logcat中验证它,其中进程id将是相同的但是线程id将是不同的。


#5楼

The best way is the clearest, most robust way: * 最好的方法是最清晰,最强大的方式:*

Thread.currentThread().equals( Looper.getMainLooper().getThread() )

Or, if the runtime platform is API level 23 (Marshmallow 6.0) or higher: 或者,如果运行时平台是API级别23(Marshmallow 6.0)或更高级别:

Looper.getMainLooper().isCurrentThread()

See the Looper API . 请参阅Looper API Note that calling Looper.getMainLooper() involves synchronization (see the source ). 请注意,调用Looper.getMainLooper()涉及同步(请参阅源代码 )。 You might want to avoid the overhead by storing the return value and reusing it. 您可能希望通过存储返回值并重用它来避免开销。

* credit greg7gkb and 2cupsOfTech * 信用greg7gkb2cupsOfTech


#6楼

你可以试试Thread.currentThread()。isDaemon()

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章