sleep()
static void sleep(longmillis)
static void sleep(longmillis, int nanos)
- 예외처리를 해야 함 (InterruptedException 발생하면 깨어남)
try {
Thread.sleep(1, 500000);
} catch(InterruptedException e) {}
- 특정 쓰레드를 지정해서 멈추게 하는 것은 불가능
public class imsi5 {
public static void main(String[] args) {
ThreadEx8_1 th1 = new ThreadEx8_1();
ThreadEx8_2 th2 = new ThreadEx8_2();
th1.start();
th2.start();
delay(2000);
System.out.println();
System.out.println("<<main 종료>>");
}
static void delay(long millis) {
try {
Thread.sleep(millis);
} catch(InterruptedException e) {}
}
}
class ThreadEx8_1 extends Thread {
public void run() {
for (int i = 0; i < 300; i++) {
System.out.print("-");
}
System.out.println();
System.out.println("<<th1 종료>>");
}
}
class ThreadEx8_2 extends Thread {
public void run() {
for (int i = 0; i < 300; i++) {
System.out.print("|");
}
System.out.println();
System.out.println("<<th2 종료>>");
}
}
interrupt()
- 대기상태(WATING)인 쓰레드를 실행대기 상태(RUNNABLE)로 변경
void interrupt()
boolean isInterrupted()
static boolean interrupted()
public class imsi6 {
public static void main(String[] args) {
ThreadEx9_1 th1 = new ThreadEx9_1();
th1.start();
String input = JOptionPane.showInputDialog("아무 값이나 입력해보세요");
System.out.println("입력하신 값은 " + input + "입니다.");
th1.interrupt();
System.out.println("isInterrupted() : " + th1.isInterrupted());
}
}
class ThreadEx9_1 extends Thread {
public void run() {
int i = 10;
while (i!=0 && !isInterrupted()) {
System.out.println(i--);
for(long x=0; x<2500000000L; x++);
}
System.out.println("카운트가 종료되었습니다.");
}
}