스레드

스레드는 여러개의 작업을 동시에 할때 필요하다. 데이터를 미리 받아서 준비해 놓거나 백그라운드로 음악을 재생할 수 도 있다. 단, 스레드를 사용할때에는 스레드간의 동기화를 고려하여 소프트웨어를 설계하여야 한다.

백드라운드 스레드는 내부적인 연산만을 해야 하며 다른 스레드 소속의 UI는 건들 수 없다. 그래서 스레드간의 통신을 할 수 있는 핸들러를 사용한다. 다음 예제를 보자


예제 소스

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class ThreadTest extends Activity {

	int mMainValue = 0;
	TextView mMainText;	
	TextView mBackText;	

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        mMainText = (TextView) findViewById(R.id.minValue);
        mBackText = (TextView) findViewById(R.id.backValue);
        Button increaseBtn = (Button) findViewById(R.id.increase);
        increaseBtn.setOnClickListener(onClick);
        
        //스레드 객체를 생성합니다.
        BackThread thread = new BackThread(mHandler);
        //데몬 스레드는 메인 스레드가 종료될때 강제 종료됨
        //무한루프 스레드의 경우에는 데몬스레드로 지정하지 않으면 결코 죽지 않는다.
        thread.setDaemon(true);	
        thread.start();
    }
    
    View.OnClickListener onClick = new View.OnClickListener() {		
		public void onClick(View v) {
			mMainValue++;
			mMainText.setText("MainValue : " + mMainValue);			
		}
	};
	
	Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			if(msg.what == 0) {
				mBackText.setText("BackValue : " + msg.arg1);
			}
		}
	};
}

class BackThread extends Thread {
	int mBackValue = 0;
	Handler mHandler;
	
	BackThread(Handler handler) {
		mHandler = handler;
	}
	
	public void run() {
		while(true) {
			//무한 반복하면서 1초에 1씩 증가
			mBackValue++;	
			Message msg = Message.obtain(mHandler, 0, mBackValue, 0);
			mHandler.sendMessage(msg);
			try {
				Thread.sleep(1000);
			} catch(InterruptedException e) {}
		}
	}
}
Posted by 피곤키오
,