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

Cha*_*ake 369 java multithreading android

我需要检查运行某段代码的线程是否是主(UI)线程.我怎样才能做到这一点?

Car*_*nal 677

Looper.myLooper() == Looper.getMainLooper()
Run Code Online (Sandbox Code Playgroud)

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


AAn*_*kit 116

您可以使用下面的代码来了解当前线程是否是UI /主线程

if(Looper.myLooper() == Looper.getMainLooper()) {
   // Current Thread is Main Thread.
}
Run Code Online (Sandbox Code Playgroud)

或者你也可以使用它

if(Looper.getMainLooper().getThread() == Thread.currentThread()) {
   // Current Thread is Main Thread.
}
Run Code Online (Sandbox Code Playgroud)

这是类似的问题

  • 是否应该将后者视为更安全的选项,因为无法保证任何任意线程与Looper相关联(假设主线程始终与looper相关联)? (8认同)

Mic*_*lan 55

最好的方法是最清晰,最强大的方式:*

Thread.currentThread().equals( Looper.getMainLooper().getThread() )
Run Code Online (Sandbox Code Playgroud)

或者,如果运行时平台是API级别23(Marshmallow 6.0)或更高级别:

Looper.getMainLooper().isCurrentThread()
Run Code Online (Sandbox Code Playgroud)

请参阅Looper API.请注意,调用Looper.getMainLooper()涉及同步(请参阅源代码).您可能希望通过存储返回值并重用它来避免开销.

   *信用greg7gkb2cupsOfTech

  • 当 Android Studio 发出警告时,这应该与 == 或 equals() 进行比较吗? (2认同)

and*_*per 23

总结解决方案,我认为这是最好的解决方案:

boolean isUiThread = VERSION.SDK_INT >= VERSION_CODES.M 
    ? Looper.getMainLooper().isCurrentThread()
    : Thread.currentThread() == Looper.getMainLooper().getThread();
Run Code Online (Sandbox Code Playgroud)

而且,如果您希望在UI线程上运行某些东西,可以使用:

new Handler(Looper.getMainLooper()).post(new Runnable() {
    @Override
    public void run() {
       //this runs on the UI thread
    }
});
Run Code Online (Sandbox Code Playgroud)


Lov*_*rma 5

你可以检查一下

if(Looper.myLooper() == Looper.getMainLooper()) {
   // You are on mainThread 
}else{
// you are on non-ui thread
}
Run Code Online (Sandbox Code Playgroud)


Kum*_*anu 5

首先检查它是否是主线程

在科特林中

fun isRunningOnMainThread(): Boolean {
    return Thread.currentThread() == Looper.getMainLooper().thread
}
Run Code Online (Sandbox Code Playgroud)

爪哇语

static boolean isRunningOnMainThread() {
  return Thread.currentThread().equals(Looper.getMainLooper().getThread());
}
Run Code Online (Sandbox Code Playgroud)