본문 바로가기
수업시간 JAVA/이론

데몬스레드

by SEOKIHOUSE 2023. 5. 18.
package 데몬스레드;

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

	@Override
	public void run() {
		while (true) {
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				System.out.println("인터럽트 발생..");
				//데몬스레드는 인터럽트 발생안함
				break; //1초쉴떄 방해발생시 반복문 끝낸다
			}
			save();
		}
		System.out.println("데몬 스레드 종료ㅋ");
	}
}
package 데몬스레드;

public class DemonEx {

	public static void main(String[] args) {
		AutoSaveThread ast = new AutoSaveThread();
		ast.setDaemon(true); //데몬스레드 하려면 !!반드시!! start되기전에 세팅
		//메인스레드가 종료되면 더이상 스레드가 실행이 안된다
		ast.start();
		
		try {
			Thread.sleep(3000);
//			ast.interrupt(); //스레드가 안될때 꺠우는역할 그 아래 sysoutㅋ 나온다
		}catch(InterruptedException e) {
			
		}
		
		System.out.println("데몬 스레드 종료");
	}

}