본문 바로가기

자바의 정석 정리

자바의 정석 - 13.7 데몬 쓰레드(Daemon Thread)

13.7.1 데몬 쓰레드

  • 일반 쓰레드의 작업을 돕는 보조적인 역할
  • 데몬 쓰레드는 일반 쓰레드 종료시 강제 종료됨
  • ex) 가바지 컬렉터, 워드 자동저장, 화면 자동 갱신
  • 무한루프와 조건문을 이용하여 실행 후 대기상태로 있다가 특정 조건 만족시 작업 수행

13.7.2 데몬 쓰레드 메서드

boolean isDeamon() //데몬 쓰레드 여부 확인
void setDeamon(boolean on) //매개변수를 true로 설정하면 데몬 쓰레드로 설정

13.7.3 데몬 쓰레드 지정

  • start()이전에 setDeamon을 호출해야 함. 그렇지 않으면 IlleThreadStateException발생
class ThreadEx implements Runnable{
    static boolean autoSave = false;

    public static void main(String[] args){
        Thread t = new Thread(new ThreadEx());
        t.setDaemon(true); 
        t.start();

        for(int i=1; i<=20; i++){
            try{
                Thread.sleep(1000); 
            }catch(InterruptedException e){ }

            System.out.println(i);
            if(i == 5) autoSave = true;
        }

        System.out.println("프로그램을 종료합니다.");
    }

    public void run(){
        while(true){
            try{
                Thread.sleep(3 * 1000);
            }catch(InterruptedException e){ }
            if(autoSave){
                autoSave();
            }
        }
    }

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