본문 바로가기

자바

[스레드] 5. 스레드 상태

객체 생성

    NEW : 스레드객체가 생성, 아직 start() 메소드가 호출되지 않은 상태

실행대기

    RUNNABLE : 실행 상태로 언제드지 갈 수 있는 상태

일시정지

    BLOCKED : 사용하고자하는 객체의 락이 풀릴 때 까지 기다리는 상태

    WAITING : 다른 스레드가 통지할  때까지 기다리는 상태

    TIMED_WAITING : 주어진 시간 동안 기다리는 상태

종료

    TERMINATED : 실행을 마친 상태

 

예제:

package thread_state;

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

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 == State.TERMINATED) {
                break;
            }

            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
package thread_state;

public class TargetThread extends Thread {
    @Override
    public void run() {
        for(long i = 0; i < 1000000000; i++) {}

        try {
            Thread.sleep(1500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        for(long i = 0; i < 1000000000; i++) {}
    }
}

실행결과:

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