programing

현재 스레드가 메인 스레드가 아닌지 확인하는 방법

minecode 2022. 10. 1. 14:04
반응형

현재 스레드가 메인 스레드가 아닌지 확인하는 방법

특정 코드를 실행하는 스레드가 메인(UI) 스레드인지 확인해야 합니다.어떻게 하면 좋을까요?

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

true가 반환되면 UI 스레드에 있는 것입니다.

아래 코드를 사용하여 현재 스레드가 UI/메인 스레드인지 여부를 알 수 있습니다.

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

또는 이것을 사용할 수도 있습니다.

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

여기 비슷한 질문이 있습니다.

가장 명확하고 견고한 방법은 다음과 같습니다.*

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

또는 런타임 플랫폼이 API 레벨 23(Marshmallow 6.0) 이상인 경우:

Looper.getMainLooper().isCurrentThread()

Looper API를 참조하십시오.콜링에 주의해 주세요.Looper.getMainLooper()는 동기화를 수반합니다(소스 참조).반환값을 저장하고 재사용함으로써 오버헤드를 피할 수 있습니다.

* 크레딧 greg7gkb2cupsOf테크놀로지

솔루션을 요약하면, 그것이 가장 좋은 방법이라고 생각합니다.

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

UI 스레드에서 무언가를 실행하려면 다음을 사용할 수 있습니다.

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

확인하실 수 있습니다.

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

이 글에 'Android' 태그가 붙어 있는 것은 인정하지만, 검색 결과는 'Android'와는 전혀 관계가 없으며, 이것이 저의 최고의 결과입니다.이를 위해 Android SO Java 이외의 사용자는 다음 사항을 잊지 마십시오.

public static void main(String[] args{
    Thread.currentThread().setName("SomeNameIChoose");
    /*...the rest of main...*/
}

이것을 설정하면, 코드의 다른 부분에서, 다음의 방법으로 메인 스레드에서 실행하려고 하는지 간단하게 확인할 수 있습니다.

if(Thread.currentThread().getName().equals("SomeNameIChoose"))
{
    //do something on main thread
}

이걸 기억하기 전에 찾아봤지만 다른 사람에게 도움이 됐으면 좋겠네요!

우선 메인 스레드인지 아닌지를 확인합니다.

인코틀린

fun isRunningOnMainThread(): Boolean {
    return Thread.currentThread() == Looper.getMainLooper().thread
}

자바어

static boolean isRunningOnMainThread() {
  return Thread.currentThread().equals(Looper.getMainLooper().getThread());
}

프로세스 ID는 같지만 스레드 ID는 다른 Android ddms logcat에서 확인할 수 있습니다.

Xamarin.Android포트:C# ( )

public bool IsMainThread => Build.VERSION.SdkInt >= BuildVersionCodes.M
    ? Looper.MainLooper.IsCurrentThread
    : Looper.MyLooper() == Looper.MainLooper;

사용방법:

if (IsMainThread) {
    // you are on UI/Main thread
}

이 행을 기록하기만 하면 "main"으로 출력됩니다.

스레드.전류스레드().name

간단한 Toast 메시지는 빠른 확인으로도 사용할 수 있습니다.

Thread.current를 사용할 수 있습니다.스레드().isDaemon()

언급URL : https://stackoverflow.com/questions/11411022/how-to-check-if-current-thread-is-not-main-thread

반응형