java,web study/3주차 (7월 15일 ~21일)
스레드 인터럽트
doublemetal
2013. 7. 17. 01:25
public class InterruptTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
ThreadInterrupt th = new ThreadInterrupt("Thread");
th.start();
try {
Thread.sleep(2000);
th.interrupt(); //2초 뒤 인터럽트
} catch (InterruptedException e) {
}
}
}
class ThreadInterrupt extends Thread {
ThreadInterrupt(String str) {
super(str);
}
public void run() {
try {
for (int i = 0; i < 10; i++) {
Thread.sleep(500);
System.out.println(getName() + " " + i + "번째 수행");
}
} catch (InterruptedException e) {
System.out.println("스레드 강제 종료");
//인터럽트 예외를 받는다.
return;
}
}
}
결과 :
Thread 0번째 수행
Thread 1번째 수행
Thread 2번째 수행
Thread 3번째 수행
스레드 강제 종료