데몬(daemon) 스레드
- 주 스레드의 작업을 돕는 보조적인 역할을 하는 스레드
- 주 스레드가 종료되면 데몬 스레드는 강제적으로 자동 종료
- e.g. 워드 프로세서의 자동 저장, 미디어 플레이어의 동영상 및 음악 재생, JVM의 가비지 컬렉터
- 데몬 스레드 설정
public static void main(String[] args){ AutoSaveThread thread = new AutoSaveThread(); thread.setDaemon(true); thread.start(); ... }
- 반드시 start( ) 메소드 호출 전에 setDaemon을 호출해야한다.
- if not → IllegalThreadStateException
- 데몬 스레드 확인 - istDaemon()
데몬 스레드 예제
public class DaemonEx { public static void main(String[] args) { AutoSaveThread autoSaveThread = new AutoSaveThread(); autoSaveThread.setDaemon(true); autoSaveThread.start(); try { Thread.sleep(30000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("main thread 종료"); } static class AutoSaveThread extends Thread{ public void save(){ System.out.println("작업 내용을 저장함."); } @Override public void run() { while(true){ //3초 단위로 저장 try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); break; } save(); } } } }
작업 내용을 저장함. 작업 내용을 저장함. 작업 내용을 저장함. 작업 내용을 저장함. 작업 내용을 저장함. 작업 내용을 저장함. 작업 내용을 저장함. 작업 내용을 저장함. 작업 내용을 저장함. main thread 종료