Language/Java
Daemon Thread
원2
2021. 4. 2. 12:40
728x90
반응형
//setDaemon
public class Ex13_7 implements Runnable { // interface
static boolean autoSave = false; // 시작하기전에 autoSave를 false로 만들어 뒀음
public static void main(String[] args) {
Thread t = new Thread(new Ex13_7()); // 내 자신을 Thread화
t.setDaemon(true); //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; // true가 될때 public void run이 시작
}
System.out.println("프로그램을 종료합니다.");
}
public void run() {
while (true) {
try {
Thread.sleep(3 * 1000); // 3초마다
} catch (InterruptedException e) {
} // autoSave의 값이 true이면 autoSave()를 호출한다.
if (autoSave)
autoSave(); //autoSave 호출
}
}
public void autoSave() {
System.out.println("작업파일이 자동저장되었습니다.");
}
}
728x90
반응형