CH13-26,27 suspend(), resume()
[자바의 정석 - 기초편] ch13-26,27 suspend(), resume()
쓰레드의 실행제어하는 메서드를 이어서 더 살펴보자. 저번시간에는 sleep()과 interrupt()를 살펴보았다.
이번시간에 살펴볼 suspend(), rewume(), stop()
는 각각 일시정지, 재개, 완전정지 기능을 한다.
suspend()는 쓰레드를 일시정지 상태로 만든다.
resume()은 일시정지가 된 쓰레드를 다시 실행대기 상태로 만든다.
stop()은 쓰레드를 소멸시킨다. (TERMINATED)
참고로 위의 세 메서드는 쓰레드를 교착상태에 빠뜨리기 쉬워서 현재는 deprecated된 상태이다.
그래서 필요할때는 아래처럼 사용자 정의해서 사용하곤 한다.
실습해보자.
public class EX13_19 {
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();
Thread.sleep(2000);
th2.suspend();
Thread.sleep(3000);
th1.resume();
Thread.sleep(3000);
th2.resume();
Thread.sleep(3000);
th1.stop();
th2.stop();
Thread.sleep(3000);
th3.stop();
} catch(InterruptedException e) {}
}
}
class MyThread implements Runnable {
volatile boolean suspended = false;
volatile boolean stopped = false;
Thread th;
public MyThread(String name) {
th = new Thread(this, name); // Thread(Runnable r, String name)
}
public void run() {
while(!stopped) {
if(!suspended)
{
System.out.println(Thread.currentThread().getName());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {}
}
}
System.out.println(Thread.currentThread().getName()+"- stopped");
}
void start() {
th.start();
}
public void suspend() {
suspended = true;
}
public void resume() {
suspended = false;
}
public void stop() {
stopped = true;
}
}
MyThread라는 클래스를 직접 만들어서 사용한다. MyThread에는 직접 정의한 suspend()와 resume(), stop()이 존재한다…
위 예제에서 주목할만한 것은 volatile
키워드이다. CPU코어들이 메모리에 있는 값을 가져올때, 참조지역성의 원리를 활용해.. 캐시 히트와 캐시 미스를 하던걸 기억하는가? 위의 코드에서 suspended와 stopped는 자주 바뀌는 값이다. 즉 CPU내부의 캐시값이 자주 바뀌어야 한다.’