Thread.sleep()이란?
예제를 살펴보기 전에 스레드(Thread)에 대해 먼저 이해할 필요가 있습니다. 스레드는 경량화된 하위 프로세스로, UI를 방해하지 않고 백그라운드 작업을 수행합니다. Thread.sleep() 메서드는 현재 실행 중인 스레드를 지정한 시간(밀리초) 동안 일시 정지시키는 역할을 합니다.
이 글에서는 안드로이드에서 Thread.sleep()을 사용하는 방법을 단계별 예제와 함께 알아보겠습니다.
1단계: 새 프로젝트 생성
Android Studio에서 새 프로젝트를 생성합니다. 상단 메뉴에서 File → New Project를 선택하고, 프로젝트 생성에 필요한 모든 세부 정보를 입력합니다.
2단계: 레이아웃 파일 작성
res/layout/activity_main.xml 파일에 아래 코드를 추가합니다.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center_horizontal"
android:layout_marginTop="100dp"
tools:context=".MainActivity">
<EditText
android:id="@+id/edit_query"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter string" />
<Button
android:id="@+id/click"
android:layout_marginTop="50dp"
style="@style/Base.TextAppearance.AppCompat.Widget.Button.Borderless.Colored"
android:layout_width="wrap_content"
android:background="#c1c1c1"
android:textColor="#FFF"
android:layout_height="wrap_content"
android:text="Button" />
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
위 코드는 EditText(텍스트 입력창)와 TextView(텍스트 출력 영역)로 구성되어 있습니다. 사용자가 EditText에 텍스트를 입력하면 5000ms(5초) 동안 대기한 후 TextView가 업데이트됩니다.
3단계: MainActivity 코드 작성
src/MainActivity.java 파일에 아래 코드를 추가합니다.
package com.example.myapplication;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
EditText edit_query;
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edit_query = findViewById(R.id.edit_query);
textView = findViewById(R.id.text);
findViewById(R.id.click).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
runthread();
}
});
}
private void runthread() {
final String s1 = edit_query.getText().toString();
Handler handler = new Handler();
handler.post(new Runnable() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
textView.setText(s1);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
});
}
}
코드 설명
버튼을 클릭하면 runthread() 메서드가 호출됩니다. 이 메서드는 Handler를 통해 Runnable을 실행하고, runOnUiThread() 내부에서 TextView에 입력한 텍스트를 설정한 뒤 Thread.sleep(5000)으로 5초간 스레드를 일시 정지시킵니다. InterruptedException은 try-catch 블록으로 처리해야 컴파일 오류가 발생하지 않습니다.
애플리케이션 실행하기
이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 열고 툴바의 Run 아이콘을 클릭하세요. 그다음 옵션 목록에서 모바일 기기를 선택하면, 기기 화면에 기본 화면이 표시됩니다.

위 실행 결과에서 확인할 수 있듯이, EditText에 텍스트를 입력하고 버튼을 클릭하면 5000ms(5초) 후에 TextView가 업데이트됩니다.
주의 사항
Thread.sleep()을 메인(UI) 스레드에서 직접 호출하면 ANR(Application Not Responding) 오류가 발생할 수 있으므로, 실제 개발 시에는 백그라운드 스레드나 Handler, Coroutine 등을 활용하는 것이 좋습니다.