자바

[스레드] 8. 데몬 스레드

devjones 2022. 5. 1. 11:50

데몬(daemon) 스레드

주 스레드의 작업을 돕는 보조적인 역할을 수행하는 스레드

주 스레드가 종료되면 데몬 스레드는 강제적으로 자동 종료

ex) 워드프로세서의 자동저장, 미디어플레이어의 동영상 및 음악 재생, 가비지 컬렉터

 

데몬 스레드 설정

주 스레드가 데몬이 될 스레드의 setDaemon(true)를 호출

public static void main(String[] args) {
    AutoSaveThread thread = new AutoSaveThread();
    thread.setDaemon(true);
    thread.start();
}

-> 반드시 start() 메소드 호출전에 setDaemon(true) 호출필

 

데몬스레드확인 방법

isDaemon()

 

예제) 메인메소드 종료시 데몬스레드도 종료되는지 확인

package ex07_daemon;

public class DaemonExample {
    public static void main(String[] args) {
        AutoSaveThread autoSaveThread = new AutoSaveThread();
        autoSaveThread.setDaemon(true);
        autoSaveThread.start();

        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("메인 스레드 종료");
        
    }
}
package ex07_daemon;

public class AutoSaveThread extends Thread {
    public void save() {
        System.out.println("작업 내용 저장");
    }

    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                break;
            }
            save();
        }
    }
}

결과:

작업 내용 저장
작업 내용 저장
메인 스레드 종료