Java Thread 状态转换

218 阅读2分钟

线程转换图

这张Java线程状态的转换图,我们在很多地方都看过,面试的八股文也背过,但大多数时候就是背过完事,知道有这么个状态。用的时候大多数时候都是线程池,或者new Thread().start。 java thread.jpeg 今天主要是想按图中的转换过程试试能不能把线程的所有状态打印出来看看。

源码中线程状态的表示

public enum State {
    /**
     * Thread state for a thread which has not yet started.
     */
    NEW,

    /**
     * Thread state for a runnable thread.  A thread in the runnable
     * state is executing in the Java virtual machine but it may
     * be waiting for other resources from the operating system
     * such as processor.
     */
    RUNNABLE,

    /**
     * Thread state for a thread blocked waiting for a monitor lock.
     * A thread in the blocked state is waiting for a monitor lock
     * to enter a synchronized block/method or
     * reenter a synchronized block/method after calling
     * {@link Object#wait() Object.wait}.
     */
    BLOCKED,

    /**
     * Thread state for a waiting thread.
     * A thread is in the waiting state due to calling one of the
     * following methods:
     * <ul>
     *   <li>{@link Object#wait() Object.wait} with no timeout</li>
     *   <li>{@link #join() Thread.join} with no timeout</li>
     *   <li>{@link LockSupport#park() LockSupport.park}</li>
     * </ul>
     *
     * <p>A thread in the waiting state is waiting for another thread to
     * perform a particular action.
     *
     * For example, a thread that has called <tt>Object.wait()</tt>
     * on an object is waiting for another thread to call
     * <tt>Object.notify()</tt> or <tt>Object.notifyAll()</tt> on
     * that object. A thread that has called <tt>Thread.join()</tt>
     * is waiting for a specified thread to terminate.
     */
    WAITING,

    /**
     * Thread state for a waiting thread with a specified waiting time.
     * A thread is in the timed waiting state due to calling one of
     * the following methods with a specified positive waiting time:
     * <ul>
     *   <li>{@link #sleep Thread.sleep}</li>
     *   <li>{@link Object#wait(long) Object.wait} with timeout</li>
     *   <li>{@link #join(long) Thread.join} with timeout</li>
     *   <li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li>
     *   <li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li>
     * </ul>
     */
    TIMED_WAITING,

    /**
     * Thread state for a terminated thread.
     * The thread has completed execution.
     */
    TERMINATED;
}

线程转换

NEW -> RUNNABLE -> TERMINATED

public static void main(String[] args) throws Exception {
    Thread t1 = new Thread(() -> {
        //System.out.println(System.currentTimeMillis());
    }, "myThread");
    System.out.printf("myThread status:%s\n", t1.getState());
    t1.start();
    System.out.printf("myThread status:%s\n", t1.getState());
    for (;;) {
        if (!t1.isAlive()) {
            System.out.printf("myThread status:%s\n", t1.getState());
            break;
        }
    }
}

打印结果:
myThread status:NEW
myThread status:RUNNABLE
myThread status:TERMINATED

WAITING<=>RUNNABLE

private static Object lock = new Object();

public static void main(String[] args) throws Exception {
    Thread t1 = new Thread(() -> {
        doSomething();
    }, "myThread");
    System.out.printf("myThread status1:%s\n", t1.getState());
    t1.start();
    System.out.printf("myThread status2:%s\n", t1.getState());
    sleep(10);
    System.out.printf("myThread status3:%s\n", t1.getState());
    wakeUp();
    System.out.printf("myThread status4:%s\n", t1.getState());
    sleep(10);
    System.out.printf("myThread status5:%s\n", t1.getState());


}

private static void wakeUp() {
    synchronized(lock) {
        lock.notify();
    }
}

private static void doSomething() {
    synchronized(lock) {
        try {
            lock.wait();
            System.out.printf(Thread.currentThread().getName()+" status6:%s\n", Thread.currentThread().getState());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
打印结果:
myThread status1:NEW
myThread status2:RUNNABLE
myThread status3:WAITING
myThread status4:BLOCKED
myThread status6:RUNNABLE
myThread status5:TERMINATED

BLOCKED<=>RUNNABLE

private static Object lock = new Object();

public static void main(String[] args) throws Exception {
    Thread t1 = new Thread(() -> {
        doSomething2();
    }, "myThread1");
    Thread t2 = new Thread(() -> {
        doSomething2();
    }, "myThread2");

    t1.start();
    t2.start();
    System.out.printf("myThread1 status:%s\n", t1.getState());
    System.out.printf("myThread2 status:%s\n", t2.getState());

}

private static void doSomething2() {
    synchronized(lock) {
        sleep(2000);
        System.out.printf(Thread.currentThread().getName()+" status:%s\n", Thread.currentThread().getState());
    }
}
打印结果:
myThread1 status:RUNNABLE
myThread2 status:BLOCKED
myThread1 status:RUNNABLE
myThread2 status:RUNNABLE