Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

Android에서 여러 스레드(Thread)를 사용하는 방법 – 단계별 예제로 배우기

예제를 살펴보기에 앞서, 먼저 스레드(Thread)가 무엇인지 간단히 짚고 넘어가겠습니다. 스레드는 경량화된 하위 프로세스(lightweight sub-process)로, UI를 방해하지 않으면서 백그라운드에서 작업을 수행할 수 있게 해줍니다. 이 글에서는 Android 앱에서 여러 개의 스레드를 동시에 사용하여 화면 요소를 업데이트하는 방법을 단계별로 알아보겠습니다.

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" />
    <TextView
        android:id="@+id/text1"
        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.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;
    TextView text1;
    boolean twice = false;
    Thread t = null;

    @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);
        text1 = findViewById(R.id.text1);
        findViewById(R.id.click).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                runthread();
                runthread1();
            }
        });
    }

    private void runthread1() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                text1.setText("tutorialspoint.com");
            }
        });
    }

    private void runthread() {
        twice = true;
        if (twice) {
            final String s1 = edit_query.getText().toString();
            t = new Thread(new Runnable() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        textView.setText(t.getName());
                        twice = false;
                    }
                });
            }
        });
        t.start();
        t.setName(s1);
        t.setPriority(Thread.MAX_PRIORITY);
        }
    }
}

코드 설명

버튼 클릭 시 runthread()runthread1() 두 메서드가 호출됩니다. 첫 번째 메서드는 사용자가 입력한 문자열을 스레드 이름으로 설정하고, 최대 우선순위(MAX_PRIORITY)로 스레드를 시작한 후 getName()으로 해당 이름을 가져와 첫 번째 TextView에 표시합니다. 두 번째 메서드는 백그라운드에서 5초간 대기한 뒤 두 번째 TextView를 "tutorialspoint.com"으로 업데이트합니다.

4단계: 앱 실행 및 결과 확인

이제 애플리케이션을 실행해 보겠습니다. 실제 Android 기기를 컴퓨터에 연결했다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤, 툴바의 Run 아이콘을 클릭하세요. 목록에서 자신의 모바일 기기를 선택하면, 기기 화면에 아래와 같은 기본 화면이 표시됩니다.

Android에서 여러 스레드(Thread)를 사용하는 방법 – 단계별 예제로 배우기

실행 결과를 보면, EditText에 임의의 텍스트를 입력하고 버튼을 클릭하면 해당 데이터가 스레드에 전달됩니다. 이후 getName() 메서드를 통해 스레드 이름을 가져와 첫 번째 TextView에 표시합니다. 동시에 두 번째 스레드는 백그라운드에서 작동하며 5초 후 TextView를 "tutorialspoint.com"으로 업데이트합니다. 이처럼 여러 스레드를 활용하면 UI를 차단하지 않고도 병렬로 작업을 처리할 수 있습니다.