예
public class Main{
static volatile boolean exit = false;
public static void main(String[] args){
System.out.println("Starting the main thread");
new Thread(){
public void run(){
System.out.println("Starting the inner thread");
while (!exit){
}
System.out.println("Exiting the inner thread");
}
}.start();
try{
Thread.sleep(100);
}
catch (InterruptedException e){
System.out.println("Exception caught :" + e);
}
exit = true;
System.out.println("Exiting main thread");
}
} 출력
Starting the main thread Starting the inner thread Exiting main thread Exiting the inner thread
메인 클래스는 새로운 쓰레드를 생성하고 그 위에서 'run' 함수를 호출합니다. 여기서 'exit'라는 부울 값이 정의되며 처음에는 false로 설정됩니다. while 루프 외부에서 'start' 함수가 호출됩니다. try 블록에서 새로 생성된 스레드는 특정 시간 동안 휴면 상태가 된 후 예외가 발생하고 관련 메시지가 화면에 표시됩니다. 이후 exit 값이 'true'로 설정되어 메인 스레드가 종료됩니다.