BACK/JAVA
[JAVA] 쓰레드의 6가지 상태
연듀
2022. 8. 26. 20:10
NEW
처음 객체 생성된 후 상태
RUNNABLE
start() 메서드로 실행한 후 상태
실행과 실행 대기를 반복하면서 CPU를 다른 쓰레드들과 나눠 가짐
일시정지 상태로 전환 가능 (TIMED_WAITING, BLOCKED, WAITING)
TERMINATED
run() 메서드 종료 후 상태
TIMED_WAITING
Thread.sleep(long millis) 또는 join(long millis) 호출: RUNNABLE -> TIME_WAITING
일시정지 시간 종료 또는 interrupt() 호출 : TIMED_WAITING -> RUNNABLE
BLOCKED
동기화 메서드 또는 동기화 블록을 실행하기 위해 먼저 실행 중인 쓰레드의 실행 완료를 기다리는 상태
앞의 쓰레드의 동기화 영역 수행이 완료되면 해당 RUNNABLE 상태가 돼 동기화 영역을 실행하게 됨
WAITING
join() 메서드 호출시 상태 - join()의 대상이 된 쓰레드가 종료되거나 interrupt() 메서드 호출시 다시 RUNNABLE로 돌아감
wait() 메서드 호출시 상태 - notify(), notifyAll() 로 RUNNABLE로 돌아감
이 때 wait(), notify(), notifyAll()은 동기화 블록 내에서만 사용 가능
public class Study{
public static void main(String[] args) {
// 쓰레드 상태 저장 클래스
Thread.State state;
// 1. 객체 생성(NEW)
Thread myThread = new Thread(){ // 익명 이너 클래스로 쓰레드 객체 생성
@Override
public void run(){
for(long i=0; i<1000000000L; i++){} // 시간 지연
}
};
state = myThread.getState(); // 쓰레드의 상태 값 가져오기 (쓰레드의 상태를 Thread.State 타입에 저장된 문자열 상숫값 중 하나로 리턴)
System.out.println("myThread state = " + state);
// 2. myThread 시작
myThread.start();
state = myThread.getState();
System.out.println("myThread state = " + state);
// 3. myThread 종료
try{
myThread.join(); // 해당 쓰레드가 완료될 때까지 main 쓰레드 일시 정지
} catch(InterruptedException e){}
state = myThread.getState();
System.out.println("myThread state = " + state);
}
}
MyThread state = NEW
MyThread state = RUNNABLE
MyThread state = TERMINATED
반응형