본문 바로가기

자바 DB 연동/쓰레드

데몬스레드

class Demo9 extends Thread{

public void run() {

for(int i=1; i<=100; i++){

System.out.println(i);

try{

sleep(100);

}catch(Exception e){

}

}

}

}


public class Test9 {

// 데몬스레드 : 다른스레드의 도움을 주기 위한 스레드로 메인스레드가 종료되면 데몬스레드도 죽는다.

// 독립스레드 : 메인 스레드가 종료되어도 독립스레드가 종료되어야 프로그램이 종료된다.


public static void main(String[] args) {

Demo9 t1=new Demo9();

Demo9 t2=new Demo9();

Demo9 t3=new Demo9();

// 데몬스레드로 만들어 주는 명령

t1.setDaemon(true);

t2.setDaemon(true);

t3.setDaemon(true);

t1.start();

t2.start();

t3.start();

// 메인끝... 출력문이 마지막에 나온다. 이 구문 없으면 중간이나 처음에 나온다. 이 try~catch 구문이 없으면 1만 3번 나온다.

try{

t1.join();

t2.join();

t3.join();

}catch(Exception e){

}

System.out.println("메인 끝...");

}


}