본문 바로가기
Tech/Java

[Java] Daemon Thread

by 소라소라잉 2019. 8. 30.

* 데몬쓰레드(daemon thread)의 이해 

 

1) 데몬 쓰레드란? : 일반 쓰레드의 작업을 돕는 보조적인 역할을 수행하는 쓰레드.

일반쓰레드가 모두 종료되면 데몬 쓰레드는 자동종료됨. 

ex) 가비지컬렉터, 워드프로세서의 자동저장, 화면 자동갱신

 

2) 작성방법 및 실행방법 : 일반 쓰레드와 같음. 단 쓰레드를 생성한 다음 실행하기 setDaemon(true)를 호출하기만 하면 됨. 데몬 쓰레드가 생성한 쓰레드는 자동적으로 데몬 쓰레드가 된다. 

 

예제)

public class ThreadEx10 implements Runnable {

    static boolean autoSave = false;

    public static void main(String[] args) {
        
        Thread t = new Thread(new ThreadEx10());
        /*
         * 아래와 같이 두줄로 쓸 수 있다. 
         * Ruannable r = new ThreadEx10();
         * Thread t = new Thread(r); 
         */
        
        /*
         *  setDaemon을 한 쓰레드는 데몬쓰레드 또는 사용자 쓰레드로 변경된다. 
         *  boolean형 매개변수의 값을 true로 지정하면 데몬쓰레드가 된다.  
         */
        
        t.setDaemon(true); // 이 부분이 없으면 종료되지 않는다.
        /*
         * 왜 종료되지 않을까? 
         * 위의 라인 없이 아래 t.start()만 실행한 경우 t는 데몬쓰레드가 아닌 일반쓰레드가 된다.
         * t는 내부에 while 무한루프를 가지고 있고 break를 할 수 있는 어떤 장치도 없다.
         * => 따라서 종료되지 않는다.
         * 그러나 t를 데몬쓰레드로 지정해주면, main메서드가 종료될 때 같이 종료된다.
         * 데몬쓰레드가 더이상 도와줄 쓰레드가 없기 때문이다. 
         */
        
        t.start(); 
        /*
         * 데몬쓰레드와 main의 for문이 실행된다. 
         * 아래 main의 for문은 1초마다 i를 출력하고
         * 데몬쓰레드는 자고있다가 i가 3일때 (처음)일어난다.
         * (3초마다 일어나게 설계되어있다.)  
         * main은 i를 증가시키다가 5가되면 static 변수인 autoSave값을 true로 변경시킨다.
         * 데몬쓰레드는 일어날때마다 autoSave가 true인지 확인하고 true면
         * autoSave()메소드를 호출해서 자동저장을 실행한다. 
         */

        for (int i = 1; i <= 10; i++) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
            }
            System.out.println(i);
            if (i == 5)
                autoSave = true;
        }
        
        System.out.println("프로그램을 종료합니다.");

    }

    @Override
    public void run() {
        while (true) {
            try {
                System.out.println("쿨쿨zzZZ");
                Thread.sleep(3 * 1000);
            } catch (InterruptedException e) {
            }
            System.out.println("일어났다!");
            if (autoSave) {
                autoSave();
            }

        }
    }

    public void autoSave() {
        System.out.println("작업파일이 자동저장되었습니다.");
    }

}

 

- 실행결과

 

* interrupt()와 interrupted() 

예제) 

import javax.swing.JOptionPane;

public class ThreadEx13 {

    public static void main(String[] args) {

        ThreadEx13_1 th1 = new ThreadEx13_1();
        th1.start();
        String input = JOptionPane.showInputDialog("아무 값이나 입력하세요.");
        System.out.println("입력하신 값은 " + input + "입니다.");
        th1.interrupt(); 
        /*
         *  인터럽트를 발생시키면 th1의 isInterrupted메서드는 자동으로 true가 되며
         *  while문 안의 조건이 false가 되어 루프가 종료된다.  
         */
        System.out.println("isInterrupted() : " + th1.isInterrupted());
    }
}

class ThreadEx13_1 extends Thread {

    @Override
    public void run() {
        int i = 10;
        while (i != 0 && !isInterrupted()) {
            System.out.println(i--);
            for (long x = 0; x < 2500000000L; x++) // 시간지연
                ; 
        }
        System.out.println("카운트가 종료되었습니다.");
    }
}

실행결과

 

 

댓글