쓰레드 강좌

출처: http://ryujt.textcube.com/37



쓰레드 소스

package app.main;

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

public class Main extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        (new PlusThread()).start();
        (new MinusThread()).start();
        
        _Button = (Button) findViewById(R.id.Button01);
        _Button.setOnClickListener(on_Click);
    }
    
    int _Count = 0;
    
    private int getCount() {
    	return _Count;
    }
    
    private void setCount(int aValue) {
    	_Count = aValue;
    }
    
    private void PlusOrMinus(int aValue) {
    	synchronized (this) {
			int _Temp;
			_Temp = getCount();
			try {
				Thread.sleep(10);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			setCount(_Temp + aValue);	
    	}
    }
    
    private Button _Button = null;
    
    private View.OnClickListener on_Click = new View.OnClickListener() {		
		public void onClick(View v) {
			_Button.setText(Integer.toString(_Count));
			
		}
	};
	
	class PlusThread extends Thread {
		public void  run() {
			for(int i=0; i<1000; i++) {
				PlusOrMinus(+1);			
			}
		}
	}	

	class MinusThread extends Thread {
		public void  run() {
			for(int i=0; i<1000; i++) {
				PlusOrMinus(-1);			
			}			
		}
	}
}
Posted by 피곤키오
,