Java/공부공부
[JAVA] Thread.sleep()
phyho
2024. 11. 27. 11:35
Thread.sleep()
현재 실행 중인 스레드의 실행을 일시적으로 멈추게 하는 메서드.
Thread.sleep(milliseconds);
Thread.sleep(milliseconds, nanoseconds);
- milliseconds : 대기 시간 (밀리초)
- nanoseconds : 추가 대기 시간 (나노초)
ex)
public class SleepExample {
public static void main(String[] args) {
System.out.println("Start");
try {
Thread.sleep(2000); // 2초 동안 멈춤
} catch (InterruptedException e) {
System.out.println("Thread was interrupted");
}
System.out.println("End");
}
}
진행중이던 스레드가 대기 상태로 변경되고, 2초 후 다시 실행.
** 해당 메소드를 호출한 스레드만 대기상태로 변경.
** 다른 스레드에 의해 중단되는 경우 InterruptedException 발생 => 예외 처리 필요.
(출력결과)
Start
(2초 대기)
End