관리 메뉴

나만을 위한 블로그

[Android] runOnUiThread란? 본문

Android

[Android] runOnUiThread란?

참깨빵위에참깨빵 2019. 11. 30. 18:59
728x90
반응형

참고한 사이트 : https://itmining.tistory.com/6

 

[안드로이드] runOnUiThread란? (개념과 사용법)

이 글은 PC 버전 TISTORY에 최적화 되어있습니다. 서론 이전 포스팅 (Thread, Handler, Looper를 이용한 백그라운드 처리) 에서 언급했듯이, 안드로이드 OS 는 UI 자원에 Main Thread와 Sub Thread가 동시 접근하..

itmining.tistory.com

https://recipes4dev.tistory.com/172

불러오는 중입니다...

 

오늘은 runOnUiThread()에 대해서 정리하는 글을 쓰려고 한다.

뒤에 ()가 붙은 걸 보면 알겠지만 메서드다.

 

안드로이드는 싱글 쓰레드 체제이며, 오직 메인 쓰레드(UI 쓰레드)만이 뷰의 값을 바꿀 수 있는 권한을 갖고 있다.

그래서 뷰의 값에 간섭하는 작업을 하는 쓰레드만을 만들고 뷰에 접근하려 시도하면, 안드로이드 자체적으로 앱을 죽여버린다. 이 경우를 막기 위해 안드로이드 개발자들은 핸들러라는 것을 만들어서 쓰도록 했다.

핸들러는 handler.post()로 메시지나 Runnable 객체를 전달하지만 이것 외에도 3가지 방법이 있다.

 

1. View.post()

2. Android.runOnUiThread()

3. AsyncTask 클래스

 

이 중 이 글의 주제인 runOnUiThread()는 디벨로퍼에서 이렇게 말하고 있다.

 

- Runs the specified action on the UI thread. If the current thread is the UI thread, then the action is executed immediately. If the current thread is not the UI thread, the action is posted to the event queue of the UI thread.

- UI 스레드에서 지정된 작업을 실행합니다. 현재 스레드가 UI 스레드이면 작업이 즉시 실행됩니다. 현재 스레드가 UI 스레드가 아닌 경우 조치(action)는 UI 스레드의 이벤트 큐에 게시됩니다.

 

지금 작업을 수행하는 쓰레드가 메인 쓰레드라면 즉시 작업을 시작하고

메인 쓰레드가 아니라면 쓰레드 이벤트 큐에 쌓아두는 기능을 하는 게 runOnUiThread다.

 

이 메서드는 액티비티 클래스에서 제공되는 메서드다. 개발자가 만든 Runnable 객체를 메인 쓰레드에서 실행되게 하는 메서드인데, 현재 메서드가 메인 쓰레드인지 여부를 검사해 메인 쓰레드가 아니라면 post()를 실행하고, 맞다면 Runnable의 run()을 실행한다.

 

그럼 구조는 어떻게 되어 있을까?

 

 

Thread.currentThread()로 현재 쓰레드가 메인 쓰레드인지 확인하고 맞으면 바로 action(Runnable)을 run()하며 아니라면 핸들러의 post()로 Runnable 객체를 넘긴다. 이 때 넘겨진 Runnable 객체는 이벤트 큐에 쌓여서 번호표를 뽑고 자기 순서가 올 때까지 기다리는 은행 방문객처럼 된다.

 

예제는 2번 사이트의 예제를 가져왔다. 디지털 시계를 구현한 예제다.

 

activity_main.xml

 

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context=".MainActivity"
tools:showIn="@layout/activity_main">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="48sp"
android:text="00:00:00"
android:id="@+id/clock"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

 

 

MainActivity.java

 

 

예제를 빌드하면 현재 시각이 1초마다 갱신된다.

코드 자체는 매우 쉬워서 주석만 봐도 이해되므로 분석은 생략했다.

반응형

'Android' 카테고리의 다른 글

[Android] 스피너란?  (0) 2019.12.01
[Android] ArrayAdapter란?  (0) 2019.12.01
[Android] AsyncTask란?  (0) 2019.11.28
[Android] Cannot open a library at FileMapping 에러  (0) 2019.11.26
[Android] 태그란?  (0) 2019.11.25
Comments