suspend(), resume(), stop()
스레드의 실행을 일시정지, 재개, 완전정지 시킨다.
void suspend() 스레드를 일시정지 시킨다.
void resume() suspend()에 의해 일시정지된 스레드를 실행대기상태로 만든다.
void stop() 스레드를 즉시 종료시킨다.
위 메서드들은 편리하지만 deprecated(사용을 권장하지 않음) 되었다. 그 이유는 교착상태(dead-lock)를 일으킬 가능성이 있기 때문이다.
class ThreadEx15 {
public static void main(String args[]) {
MyThread th1 = new MyThread("*");
MyThread th2 = new MyThread("**");
MyThread th3 = new MyThread("***");
th1.start();
th2.start();
th3.start();
try {
Thread.sleep(2000);
th1.suspend(); // 쓰레드 th1을 잠시 중단시킨다.
Thread.sleep(2000);
th2.suspend();
Thread.sleep(3000);
th1.resume(); // 쓰레드 th1이 다시 동작하도록 한다.
Thread.sleep(3000);
th1.stop(); // 쓰레드 th1을 강제종료시킨다.
th2.stop();
Thread.sleep(2000);
th3.stop();
} catch (InterruptedException e) {}
} // main
}
class MyThread implements Runnable {
volatile boolean suspended = false; // volatile 쉽게 바뀌는 변수
volatile boolean stopped = false;
Thread th;
MyThread(String name) {
th = new Thread(this, name); // Thread(Runnable r, String name)
}
void start() {
th.start();
}
void stop() {
stopped = true;
}
void suspend() {
suspended = true;
}
void resume() {
suspended = false;
}
public void run() {
while(!stopped) {
if(!suspended) {
System.out.println(Thread.currentThread().getName());
try {
Thread.sleep(1000);
} catch(InterruptedException e) {}
}
}
} // run()
}
'JAVA' 카테고리의 다른 글
[Thread] 스레드의 동기화 - synchronized (0) | 2023.02.27 |
---|---|
[Thread] join(), yield() (0) | 2023.02.27 |
[Thread] sleep(), interrupt()와 interrupted() (0) | 2023.02.26 |
[Thread] 데몬 스레드, 스레드의 상태 (0) | 2023.02.26 |
[Thread] 스레드의 우선순위 (0) | 2023.02.26 |