JAVA

자바 쓰레드 생성 및 종료

AJ Styles 2018. 4. 6. 17:57

- 쓰레드 생성 


Runnable r = new 쓰레드클래스();

Thread th = new Thread(r);

th.start();



- 쓰레드 종료


interrupt() 함수를 이용하는 방법


1. try { 

while(!Thread.currentThread.isInterrupted()) {

// 인터럽트가 발생하지 않는경우 실행할 명령

...

// 특정 조건에서 인터럽트 발생시킴 Thread.currentThread().interrupt()

...

// 인터럽트가 발생할 경우를 대비하여 Thread.sleep() 함수 구현

}

   } 

   catch(InterruptedException e) {

 // 인터럽트 발생시 실행

   }


2. 쓰레드 내부에서 인터럽트 interrupt() 함수 호출


3. Thread.sleep() 부분에서 인터럽트 발생


4. try ~ catch 블록 실행


5. run() 함수 종료


6. 쓰레드 종료



- 예제


public class Test01 {


public static Thread initThread;

public static Runnable r;


public static void main(String[] args) {


r = new Init_Thread();

initThread = new Thread(r);

initThread.start();


}


}


class Init_Thread implements Runnable {


private int count;


@Override

public void run() {

// TODO Auto-generated method stub

count = 0;


try {

while (!Thread.currentThread().isInterrupted()) {

System.out.println("타냐?");

System.out.println("I'm Alive!");

count++;

if (count == 5) {

Thread.currentThread().interrupt();

}

Thread.sleep(1000);

System.out.println("시간");

}


} catch (InterruptedException e) {

// TODO: handle exception

System.out.println("인터럽트 발생");

System.out.println("쓰레드 종료!");

}

System.out.println("끝");

}


}