[Android] 안드로이드 스튜디오 쓰레드(thread) 사용 예시

    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:gravity="center"
    android:orientation="vertical"
    tools:context=".MainActivity">
    
    <TextView
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!"
    android:textSize="28dp"
    android:textColor="#AA0000"
    />
    
    <TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!"
    android:textColor="#AA0000"
    android:textSize="28dp"
    />
    
    </LinearLayout>

     

    자바파일

    package com.example.a25thread;
    
    import android.os.Handler;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.util.Log;
    import android.widget.TextView;
    
    public class MainActivity extends AppCompatActivity {
    	private Thread thread;
    	private TextView textView;
    	private TextView textView1;
    	private int number = 0;
    	private int num = 10000;
    
    	@Override
    	protected void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    		setContentView(R.layout.activity_main);
    
    		textView = (TextView) findViewById(R.id.textView);
    		textView1 = (TextView) findViewById(R.id.textView1);
    
    		thread = new Thread() { // 쓰레드 생성
    			public void run() {
    				super.run();
    
    				while (true) { // 무한반복
    					try {
    						sleep(1000);
    					} catch (InterruptedException e) {
    						e.printStackTrace();
    					}
    
    					number++;
    					Log.i("test", "thread running..." + number++);
    
    					runOnUiThread(new Runnable() {
    						public void run() {
    							textView.setText(String.valueOf(number));
    						}
    					});
    				}
    
    			}
    		};
    
    		thread.start();
    
    		thread = new Thread() {
    			public void run() {
    				super.run();
    
    				while (true) {
    					try {
    						sleep(1000);
    					} catch (InterruptedException e) {
    						e.printStackTrace();
    					}
    
    					num--;
    					Log.i("test", "thread running..." + num--);
    
    					runOnUiThread(new Runnable() {
    						public void run() {
    							textView1.setText(String.valueOf(num));
    						}
    					});
    				}
    
    			}
    		};
    
    		thread.start();
    	}
    }
    

     

     

    출력 이미지

    헬로 월드라는 문구가 출력되고

    첫번째는 0부터 1000까지 2씩 증가하고

    두번째는 1000부터 0까지 2씩 감소하게된다.

    댓글

    Designed by JB FACTORY