1 답변
-
Deamon Thread(데몬쓰레드)
- 다른 일반 쓰레드(데몬 쓰레드가 아닌)의 작업을 돕는 보조적인 역할을 수행하는 쓰레드이다.
- 일반 쓰레드가 모두 종료되면 데몬 쓰레드는 강제적으로 자동종료된다.
- 데몬쓰레드가 생성한 쓰레드는 자동으로 데몬 쓰레드가 된다.
- 예) 가비지컬렉터, 워드프로세서의 자동저장, 화면자동갱신 등
boolean isDaemon() // 쓰레드가 데몬 쓰레드인지 확인한다. void setDaemon(boolean on) // 쓰레드를 데몬 쓰레드 또는 사용자 쓰레드로 // 변경한다.
예제)소스코드
import java.util.*; class example implements Runnable{ static boolean autoSave = false; public static void main(String[] args) { Thread t = new Thread(new example()); 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("프로그램을 종료합니다."); } @Override public void run() { while(true) { try{ Thread.sleep(3 * 1000); }catch(InterruptedException e){} if(autoSave) autoSave(); } } private void autoSave() { System.out.println("작업파일이 자동저장되었습니다."); } }
여기서
t.setDaemon(true);
이 되지않았다면 계속 무한루프를 돌았을겁니다.
댓글 입력