1.데몬 스레드, Demon Thread


Main이 종료 될 때 직접 작성한 스레드들은 따로 끝내지 않으면 계속 돌아가게 되는데


Thread가 많아 질 수록 리소스를 많이 가져가고


꺼지지 않은 Thread가 만약 공유하는 변수값을 수정한다면 프로그램 자체가 꼬이게 된다.


그래서 스레드 start 전에 setDaemon(true) 설정을 하면


스레드를 실행한 메인 스레드가 종료된다면 강제로 같이 종료가 된다.


다음 예를 보자


package chap10.exam12.demon;

public class DemonThread extends Thread {

	@Override
	public void run() {		
		while(true) {
			System.out.println("Demon Thread Running...");
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
}
<


package chap10.exam12.demon;

public class MainThread {

	public static void main(String[] args) throws InterruptedException {
		Thread demon = new DemonThread();
		demon.setDaemon(true);//work -> demon
		demon.start();//데몬 스레드 시작
		Thread.sleep(3000);//3초후
		System.out.println("메인 스레드 종료");
	}

}


+ Recent posts