본문 바로가기
모바일 앱/Android

[Android] Thread 구현

by 테크케찰 2020. 11. 29.

오늘은 안드로이드 스튜디오에서 Thread를 구현하는 것을 정리해보려 합니다.

간단하게 1초에 한 번씩 로그 메시지를 띄워주는 코드를 작성해보겠습니다.

 

1) Thread 클래스를 상속받아서 작성

  xml 파일에는 별다른 코딩을 해주지 않고 MainActivity.java 파일에만 이렇게 코딩을 해주었습니다.

package com.example.threadex2;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private static String TAG="MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Thread1 thread1=new Thread1();
        thread1.start();
    }

    class Thread1 extends Thread{
        public Thread1() {
            super();
        }

        @Override
        public void run() {
            super.run();
            for(int i=0;i<5;i++){
                Log.d(TAG, "Thread 실행중 "+i);
                try {
                    Thread.sleep(1000); // Thread 1초동안 일시정지
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }
    }

}

이 결과 아래와 같은 로그 결과를 얻을 수 있었습니다. 

2020-11-29 17:44:57.018 12746-12800/com.example.threadex2 D/MainActivity: Thread 실행중 0
2020-11-29 17:44:58.020 12746-12800/com.example.threadex2 D/MainActivity: Thread 실행중 1
2020-11-29 17:44:59.021 12746-12800/com.example.threadex2 D/MainActivity: Thread 실행중 2
2020-11-29 17:45:00.022 12746-12800/com.example.threadex2 D/MainActivity: Thread 실행중 3
2020-11-29 17:45:01.024 12746-12800/com.example.threadex2 D/MainActivity: Thread 실행중 4

 

2) Runnable 인터페이스 구현

package com.example.threadex2;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private static String TAG="MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Runnable1 runnable1=new Runnable1();
        Thread thread=new Thread(runnable1);
        thread.start();
    }

        class Runnable1 implements Runnable {

            @Override
            public void run() {
                for(int i=0;i<5;i++){
                    Log.d(TAG, "Thread 실행중 "+i);
                    try {
                        Thread.sleep(1000); // Thread 1초동안 일시정지
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

}

결과는 아래와 같이 얻을 수 있습니다.

2020-11-29 17:43:50.132 12644-12692/com.example.threadex2 D/MainActivity: Thread 실행중 0
2020-11-29 17:43:51.133 12644-12692/com.example.threadex2 D/MainActivity: Thread 실행중 1
2020-11-29 17:43:52.135 12644-12692/com.example.threadex2 D/MainActivity: Thread 실행중 2
2020-11-29 17:43:53.137 12644-12692/com.example.threadex2 D/MainActivity: Thread 실행중 3
2020-11-29 17:43:54.138 12644-12692/com.example.threadex2 D/MainActivity: Thread 실행중 4

 

3) Thread 중지시키기

activity_main.xml 파일에 다음과 같이 버튼을 하나 만들어주었습니다.

이 버튼을 클릭하면 쓰레드를 중지시킬 겁니다.

<?xml version="1.0" encoding="utf-8"?>
<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"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/Button_thread"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="쓰레드 중지"
        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

package com.example.threadex2;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private static String TAG="MainActivity";
    private boolean isThread=true;
    private Button Button_thread;
    private Thread thread1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button_thread=findViewById(R.id.Button_thread);

        thread1=new Thread1();
        thread1.start();

        Button_thread.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                isThread=false;
            }
        });
    }

    class Thread1 extends Thread{
        public Thread1() {
            super();
        }

        @Override
        public void run() {
            super.run();
            while(isThread){
                Log.d(TAG, "Thread 실행중");
                try {
                    Thread.sleep(1000); // Thread 1초동안 일시정지
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }
    }

}

isThread라는 boolean 값을 이용해서 true일 때는 실행되도록, false가 되면 실행이 되지 않도록 코딩을 해주었고, 버튼을 클릭하면 isThread라는 변수가 false가 되도록 하였습니다.

여기서 쓰레드를 다시 시작하려면 객체를 다시 생성하는 방법 등을 이용하시면 됩니다.