
* 겪고 있는 문제 상황을 최대한 자세하게 작성해주세요.
* 문제 해결을 위해 어떤 시도를 해보았는지 구체적으로 함께 알려주세요.
강의에서 !Thread.currentThread().isInterrupted()로 interrupted 상태를 체크해서 처리하면 오류를 방지할 수 있다고 하셨는데,
while문 조건으로 인하여 인터럽트가 발생하지 않을 때 try~catch문이 실행되는데
그러면 굳이 while문 안에 InterruptedException 을 적는 이유가 뭔가요?
sleep()메소드 자체에 throws를 통해서 예외선언을 해놓아서 메소드를 쓸 때 try~catch문을 통해 핸들링을 꼭 해줘야 한다는 것은 알고 있습니다!
public class Main {
public static void main(String[] args) {
Runnable task = () -> {
while (!Thread.currentThread().isInterrupted()) {
try {
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName());
} catch (InterruptedException e) {
break;
}
}
System.out.println("task : " + Thread.currentThread().getName());
};
Thread thread = new Thread(task, "Thread");
thread.start();
thread.interrupt();
System.out.println("thread.isInterrupted() = " + thread.isInterrupted());
}
}
