예제를 살펴보기에 앞서, 안드로이드에서 스레드(Thread)가 무엇인지 먼저 짚고 넘어가겠습니다. 스레드는 대부분의 작업을 수행할 수 있는 일반적인 처리 단위이지만, 단 한 가지 할 수 없는 작업이 바로 UI를 직접 갱신하는 것입니다.
이 글에서는 안드로이드에서 지속적으로(continuously) 실행되는 스레드를 구현하는 방법을 단계별 예제와 함께 알아보겠습니다.
1단계: 새 프로젝트 생성
Android Studio에서 File ⇒ New Project를 선택한 후, 새 프로젝트 생성에 필요한 모든 정보를 입력하여 프로젝트를 만듭니다.
2단계: 레이아웃 코드 추가
res/layout/activity_main.xml 파일에 다음 코드를 추가합니다.
<?xml version = "1.0" encoding = "utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android = "https://schemas.android.com/apk/res/android"
xmlns:app = "https://schemas.android.com/apk/res-auto"
xmlns:tools = "https://schemas.android.com/tools"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
tools:context = ".MainActivity">
<TextView
android:id = "@+id/text"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:text = "Continues thread"
android:textSize = "25sp"
app:layout_constraintBottom_toBottomOf = "parent"
app:layout_constraintLeft_toLeftOf = "parent"
app:layout_constraintRight_toRightOf = "parent"
app:layout_constraintTop_toTopOf = "parent" />
</android.support.constraint.ConstraintLayout>
위 코드에는 TextView 하나만 배치되어 있습니다. 사용자가 이 TextView를 클릭하면 지속적으로 실행되는 스레드가 시작되고, 그 결과가 Logcat에 출력됩니다.
참고: 최신 Android Studio 프로젝트는 AndroidX를 기본으로 사용하므로,
android.support.constraint.ConstraintLayout대신androidx.constraintlayout.widget.ConstraintLayout을 사용하는 것이 좋습니다.
3단계: MainActivity 코드 추가
src/MainActivity.java 파일에 다음 코드를 추가합니다.
package com.example.andy.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = findViewById(R.id.text);
text.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Thread(new Runnable() {
@Override
public void run() {
while (true)
Log.d("Continues thread", "Tutorialspoint.com");
}
}).start();
}
});
}
}
핵심은 run() 메서드 안의 while(true) 무한 루프입니다. 이 루프 덕분에 스레드가 종료되지 않고 계속해서 로그 메시지를 출력하게 됩니다.
앱 실행 및 결과 확인
이제 애플리케이션을 실행해 보겠습니다. 실제 Android 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바의 Run 아이콘을 클릭하고 옵션 목록에서 자신의 모바일 기기를 선택하세요. 그러면 기기 화면에 아래와 같은 기본 화면이 표시됩니다.

위 결과는 앱의 기본 화면입니다. 여기서 사용자가 TextView를 클릭하면 스레드가 계속 실행되며, Logcat에서 다음과 같이 반복적으로 출력되는 로그를 확인할 수 있습니다.

마무리 및 주의 사항
이처럼 while(true) 루프를 활용하면 스레드를 지속적으로 실행할 수 있습니다. 다만 실무에서는 무한 루프가 CPU 자원을 계속 점유하므로, Thread.sleep()으로 실행 간격을 조절하거나, 종료 조건 플래그를 두어 스레드를 안전하게 중단할 수 있도록 설계하는 것이 좋습니다. 또한 백그라운드 작업이 필요하다면 HandlerThread, ExecutorService, Kotlin Coroutines 같은 더 효율적인 대안도 함께 고려해 보세요.