출처: https://3months.tistory.com/307 [Deep Play]

안드로이드/연습

[Android] Thread

코딩하는 랄뚜기 2021. 8. 29. 23:08

activity_main.xml

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

    <SeekBar
        android:id="@+id/pb1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
    <SeekBar
        android:id="@+id/pb2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="스레드 시작"/>


</LinearLayout>

MainActivity.java

package com.example.thread;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;

public class MainActivity extends AppCompatActivity {
    ProgressBar pb1,pb2;
    Button btn;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        pb1 = (ProgressBar) findViewById(R.id.pb1);
        pb2 = (ProgressBar) findViewById(R.id.pb2);
        btn = (Button) findViewById(R.id.button1);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new Thread(){
                    public void run(){
                        for(int i=pb1.getProgress();i<100;i+=2){
                            pb1.setProgress(pb1.getProgress()+2);
                            SystemClock.sleep(100);
                        }
                    }
                }.start();
                new Thread(){
                    public void run(){
                        for(int i=pb2.getProgress();i<100;i++){
                            pb2.setProgress(pb2.getProgress()+1);
                            SystemClock.sleep(100);
                        }
                    }
                }.start();
            }
        });
    }
}

배운 점

thread를 사용하면 변수값이 바뀔 때마다 바로 화면을 업데이트 해줘서 좀 더 동적인 UI를 구현 할 수 있다. 앱을 만들기 위해서는 필수로 알아두어야 한다.

 

실행 화면