1. suspend(), resume(), stop()
- 쓰레드의 실행을 일시정지, 재개, 완전정지 시킨다.
void suspend() // 쓰레드를 일시정지 시킨다.
void resume() // suspend()에 의해 일시정지된 쓰레드를 실행대기상태로 만든다.
void stop() // 쓰레드를 즉시 종료시킨다.
// deprecated (사용권장X) dead-lock 교착상태를 발생시킴
- suspend(), resume(), stop()은 교착상태에 빠지기 쉬워서 deprecated되었다.
class ThreadEx17_1 implements Runnable { // 직접 suspend(), resume(), stop()을 코딩한다.
boolean suspended = false; // 일시정지 상태인가?
boolean stopped = false; // 정지 상태인가?
public void run() {
while(!stopped) { // true
if(!suspended) { // true
/* 쓰레드가 수행할 코드를 작성 */
}
}
}
public void suspend() { suspended = true; }
public void resume() { suspended = false; }
public void stop() { stopped = true; }
}
2. 예제
public class Ex_07 {
public static void main(String[] args) {
RunImplEx10 r = new RunImplEx10();
Thread th1 = new Thread(r, "*");
Thread th2 = new Thread(r, "**");
Thread th3 = new Thread(r, "***");
th1.start();
th2.start();
th3.start();
// deprecated된 메서드들
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) {}
}
}
class RunImplEx10 implements Runnable {
public void run() {
while (true) {
System.out.println(Thread.currentThread().getName());
try{
Thread.sleep(1000);
} catch(InterruptedException e) {}
}
}
}
3. 예제
public class Ex_07 {
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) {}
}
}
class MyThread implements Runnable {
volatile boolean suspended = false; // 쉽게 바뀌는 변수
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) {}
}
}
}
}
'Java' 카테고리의 다른 글
134. 쓰레드의 동기화 - 패스트캠퍼스 백엔드 부트캠프 3기 (0) | 2025.01.07 |
---|---|
133. join(), yield() - 패스트캠퍼스 백엔드 부트캠프 3기 (0) | 2025.01.07 |
131. sleep(), interrupt() - 패스트캠퍼스 백엔드 부트캠프 3기 (0) | 2025.01.07 |
130. 데몬 쓰레드, 쓰레드의 상태 - 패스트캠퍼스 백엔드 부트캠프 3기 (0) | 2025.01.06 |
129. 쓰레드의 우선순위, 쓰레드 그룹 - 패스트캠퍼스 백엔드 부트캠프 3기 (2) | 2025.01.06 |