본문 바로가기

구글과인터넷/안드로이드

안드로이드 쓰레드 중지(죽이기) 시키기

안드로이드 스레드는 한 사이클이 끝나지 않으면 죽지 않는 것 같다

그러므로 While 문이라던가 for 문같은 반복문을 사용하게 되면

해당 반복문이 끝나기 전에는 죽지 않는다..

 

아래 소스는 최초 클릭시 스레드를 시작시키고 재 클릭시에는

기존스레드를 멈추고

새로운 스레드를 사용하는 예제이다 (업무상 사용한 예제를 수정한 것이라 사소한 에러가 있을수 있다)

 

스레드를 멈추는 방법으로는 interrupt() 를 사용하였다.

클릭 이벤트의  thread.interrupt() 와

thread Class 의 run() 속의 while (!this.interrupted()) 을 사용

 

===================================================================================

//스레드 클레스  DeviceThread.java

 

Thread thread = null;     //Class 변수로 thread 설정

public void onClick(View v) {

 

 if (thread != null && thread.isAlive()){                 //thread가 살아있을경우 멈추고 재실행 죽었을경우 새로 생성 실행
      thread.interrupt();  //기존 스레드를 멈춤
      
      thread = new DeviceThread("파레메타");
      thread.start();
      thread.stop();
      Log.d("@@@@@@@@@@@@@@", "thread destory and create thread=" + thread.getId());
     }
     else { 
      thread = new DeviceThread(controllerData, Integer.parseInt((String)tvTmp.getText()));      
      Log.d("@@@@@@@@@@@@@@", "thread first create thread=" + thread.getId());
      thread.start();
      thread.stop();      
     }

}

 

===================================================================================

//스레드 클레스  DeviceThread.java

public class DeviceThread extends Thread{

 int intTimer = 0;

 public DeviceThread(int position)
 {
  threadControllerData = controllerData;
  threadPosition = position;
 }

 

 public void run() {
  while (!this.interrupted()) {   //인터럽트를 확인하여 스레드를 빠져 나간다
   SystemClock.sleep(1000);
   //Thread.sleep(5000);


   if (intTimer == 4) {
    this.interrupt();
    RequestService();  //4초 후 실행시킬 서비스
   }
   intTimer++;
  }
  Log.d("@@@@@@@@@@@@@@@@@", "intTimer out ground ");  //While 문을 빠져나간후에도 스레드가 계속 도는지 확인하기 위해
 };

 

 

 public void RequestService(){

       //실행할 코드
 }
}