13-26~27 suspend(), resume(), stop()

oyeon·2020년 12월 31일
0

Java 개념

목록 보기
56/70
  • 쓰레드의 실행을 일시정지, 재개, 완전정지 시킨다.
  • suspend(), resume(), stop()은 교착상태에 빠지기 쉬워서 deprecated 되었다.
  • 다음과 같은 방식으로 직접 구현할 수 있다.
// 구현
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)
    }
    
    public void run() {
    	while(!stopped) {
        	if(!suspended) {
            	/* 쓰레드가 수행할 코드를 작성 */
                System.out.println(Thread.currentThread().getName());
                try{
                    Thread.sleep(1000);
                } catch(InterruptedException e) {}
            }
        }
    }
    public void suspend() { suspended =true; }
    public void resume() { suspended =false; }
    public void stop() { stopped = true; }
}
// 사용
public practice {
    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();	// 쓰레드 th2를 잠시 중단시킨다.
            Thread.sleep(3000);
            th1.resume();	// 쓰레드 th1을 다시 동작시킨다.
            Thread.sleep(3000);
            th1.stop();	// 쓰레드 th1을 강제 종료시킨다.
            th2.stop();	// 쓰레드 th2를 강제 종료시킨다.
            Thread.sleep(2000);
            th3.stop();	// 쓰레드 th3를 강제 종료시킨다.
        } catch (InterruptedException e) {}
    }
}

volatile

  • RAM에 올라간 변수 suspended 값 false를 CPU의 코어 내에 cache 메모리가 더 빠른 작업을 위해 복사해서 갖고 있다.
  • RAM이 갖고 있는 원본 suspended의 값이 false에서 true로 변할 때, cache 메모리의 복사본 suspend의 값은 변하지 않을 수 있다.
  • volatile을 붙이면 복사본을 사용하지 않고, RAM의 원본을 직접 읽어온다.
  • 자주 바뀌는 값이니까 복사본 쓰지않고, 원본에서 값을 가져다 쓰라는 뜻.
profile
Enjoy to study

0개의 댓글