2016-07-20 1 views
-2
public static void main(String s[]) 
{ 
    Thread t=Thread.currentThread(); 
    t.setName("main"); 
    try 
    { 
     for(int i=0;i<=5;i++) 
     { 
      System.out.println(i); 
      Thread.sleep(1000);//interrupted exception(System provides error on its own) 
     } 
    } 
    catch(InterruptedException e) 
    { 
     System.out.println("main thread interrupted"); 
    } 
} 

`예외 상황이있을 때 컨트롤이 catch로 이동하여 코드를 남깁니다. 우리가 thread.sleep을 사용하고 interruptedException에 대한 catch를 만들면 왜 계속 실행됩니까? 그 대신에. 이 코드는 for 루프가 처음 실행될 때 thread.sleep을 만날 때 "0"을 출력하므로 interruptedexception이 발생하면 SO.O.P를 catch하고 실행하고 종료해야합니까?왜 처음 catch에서 thread.sleep이 멈 춥니 까?

+2

음 ... 'sleep'이 종료되는 예외를 트리거 했습니까? –

+1

당신이 말하지 않으면 왜 끝내겠습니까? –

답변

0

왜 계속 실행됩니까?

귀하가 말씀하시지 않는 한 프로그램이 종료되지 않습니다. 그것은 정상적으로 달리기를 계속합니다. 예외를 트리거해도 변경되지 않습니다.

0

그냥 Thread.sleep을 호출해도 InterruptedException이 발생하지 않습니다. 이 코드가 InterruptedException을 던지려면 스레드에서 인터럽트를 호출해야합니다.

public class MainInterruptingItself { 

    public static void main(String s[]) { 
     Thread.currentThread().interrupt(); 
     try { 
      for(int i=0;i<=5;i++) { 
       System.out.println(i); 
       Thread.sleep(1000); 
      } 
     } 
     catch(InterruptedException e) { 
       System.out.println("main thread interrupted"); 
     } 
    } 
} 

에 코드를 변경하고 여기에 어떻게됩니까

0 
main thread interrupted 

인터럽트를 호출하면 스레드에 인터럽트 플래그를 설정한다는 것입니다 밖으로 인쇄됩니다. Thread.sleep이 실행되면 인터럽트 플래그가 설정되고이를 기반으로 InterruptedException이 throw됩니다.

관련 문제