프로그래밍 노트/JAVA

[JAVA] 스레드 상태(Thread_3)

깡냉쓰 2019. 3. 2. 14:25
728x90
반응형

스레드 상태


처음에 start() 메소드를 호출하면 곧바로 스레드가 실행되는 것처럼 보이지만 사실은 실행 대기 상태가 된다.

스레드 스케줄링으로 선택된 스레드가 비로서 CPU를 점유하고 run()메소드를 실행한다. => 실행(Running)상태


 

상태열거 상수설명
객체 생성NEW스레드 객체가 생성, 아직 start() 메소드가 호출되지 않음
실행 대기RUNNABLE실행 상태로 언제든지 갈 수 있는 상태
일시 정지WAITING다른 스레드가 통지할 때까지 기다리는 상태
일시 정지TIMED_WAITING주어진 시간 동안 기다리는 상태
일시 정지BLOCKED사용하고자 하는 객체의 락이 풀릴 때까지 기다리는 상태
종료TERMINATED실행을 마친 상태

 

예제 코드

public class StatePrintThread extends Thread{
	// 타겟 스레드의 상태를 출력하는 스레드
	
	private Thread targetThread;
	
	public StatePrintThread(Thread targetThread) {
		this.targetThread = targetThread;
	}

	@Override
	public void run() {
		while(true){
			Thread.State state = targetThread.getState();
			System.out.println("타겟 스레드 상태 : " + state);
			
			if(state == Thread.State.NEW){
				targetThread.start(); // 실행대기 상태로 만듬
			}
			
			if(state == Thread.State.TERMINATED){
				break;
			}
			
			try{
				Thread.sleep(500);
			}catch(Exception e){}
		}
	}
}

public class TargetThread extends Thread{
	
	@Override
	public void run() {
		
		for(long i=0; i<1000000000; i++){
			// RUNNABLE 상태 유지
		}
		
		try{
			Thread.sleep(1500); // 1.5 초간 TIMED_WAITING 상태 유지
		}catch(Exception e){}
		
		for(long i=0; i<1000000000; i++){
			// RUNNABEL 상태 유지
		}
		
	}
}

public class ThreadStateExample {
	public static void main(String[] args){
		StatePrintThread statePrintThread = new StatePrintThread(new TargetThread());
		statePrintThread.start();
	}
}

결과 값

타겟 스레드 상태 : NEW
타겟 스레드 상태 : RUNNABLE
타겟 스레드 상태 : TIMED_WAITING
타겟 스레드 상태 : TIMED_WAITING
타겟 스레드 상태 : TIMED_WAITING
타겟 스레드 상태 : RUNNABLE
타겟 스레드 상태 : RUNNABLE
타겟 스레드 상태 : TERMINATED

 

728x90
반응형