Thread狀態(tài)

一、Thread中對狀態(tài)定義的枚舉

    /**
     * A thread state.  A thread can be in one of the following states:
     * <ul>
     * <li>{@link #NEW}<br>
     *     A thread that has not yet started is in this state.
     *     </li>
     * <li>{@link #RUNNABLE}<br>
     *     A thread executing in the Java virtual machine is in this state.
     *     </li>
     * <li>{@link #BLOCKED}<br>
     *     A thread that is blocked waiting for a monitor lock
     *     is in this state.
     *     </li>
     * <li>{@link #WAITING}<br>
     *     A thread that is waiting indefinitely for another thread to
     *     perform a particular action is in this state.
     *     </li>
     * <li>{@link #TIMED_WAITING}<br>
     *     A thread that is waiting for another thread to perform an action
     *     for up to a specified waiting time is in this state.
     *     </li>
     * <li>{@link #TERMINATED}<br>
     *     A thread that has exited is in this state.
     *     </li>
     * </ul>
     *
     * <p>
     * A thread can be in only one state at a given point in time.
     * These states are virtual machine states which do not reflect
     * any operating system thread states.
     *
     * @since   1.5
     * @see #getState
     */
    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;
    } 

二、狀態(tài)解釋

<p>NEW:線程被創(chuàng)建,還沒有調(diào)用start()方法。
<p>RUNNABLE:線程調(diào)用start()方法后的狀態(tài),這個時候可能還沒有真正的運行,有可能還在等待系統(tǒng)資 源,可能還沒獲得CPU。
<p>BLOCKED: 線程處于阻塞狀態(tài),等待鎖釋放。等待進入synchronized方法或者代碼塊時會進入這種狀態(tài)。
<p>WAITING:等待狀態(tài),當線程調(diào)用Thread.sleep()方法、或者調(diào)用Object.wait()方法、或者有其他線程調(diào)用Thread.join方法、或者線程調(diào)用LockSupport.park()方法時會處于這種狀態(tài)。
<p>TIMED_WAITING:和WAITING狀態(tài)類似,但是會指定等待的時間。調(diào)用Thread.sleep(long)、Object.wait(long)、Thread.join(long)、LockSupport.parkNanos(long)、LockSupport.parkUntil(Object blocker, long deadline)的時候會進入這個狀態(tài)
<p>TERMINATED:進程結束

三、引申--synchronized和ReentrantLock實現(xiàn)“阻塞”時的線程狀態(tài)的區(qū)別

小伙伴們?nèi)タ碦eentrantLock的源碼就知道,ReentrantLock是通過LockSupport.park實現(xiàn)阻塞的。所以synchronized實現(xiàn)阻塞后,等待的線程狀態(tài)是BLOCKED狀態(tài),而通過ReentrantLock實現(xiàn)阻塞后,現(xiàn)成的狀態(tài)是WAITING狀態(tài)??聪旅嬉粋€栗子:

class TestObject {
   public void testMethod(){
        synchronized (TestObject.class){
            try {
                Thread.sleep(1000000000000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

class SynchronizedThread extends Thread{
    @Override
    public void run() {
        TestObject to = new TestObject();
        to.testMethod();
    }
}

public class Test {
    public static void main(String[] args) {
        SynchronizedThread st1 = new SynchronizedThread();
        SynchronizedThread st2 = new SynchronizedThread();
        st1.setName("1111111111");
        st2.setName("2222222222");
        st1.start();
        try {
            Thread.sleep(1000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        st2.start();
    }
}

運行后通過jstack命令查看線程狀態(tài):

Paste_Image.png

可以看到線程命是‘2222222222’的線程狀態(tài)是BLOCKED

修改一下代碼:

class TestObject {
    ReentrantLock lock;
    public TestObject(ReentrantLock lock){
        this.lock = lock;
    }
    public void testMethod(){
        lock.lock();
        try {
            Thread.sleep(1000000000000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}

class SynchronizedThread extends Thread{
    ReentrantLock lock;
    public SynchronizedThread(ReentrantLock lock){
        this.lock = lock;
    }
    @Override
    public void run() {
        TestObject to = new TestObject(lock);
        to.testMethod();
    }
}

public class Test {
    ReentrantLock lock = new ReentrantLock();
    public static void main(String[] args) {
        ReentrantLock lock = new ReentrantLock();
        SynchronizedThread st1 = new SynchronizedThread(lock);
        SynchronizedThread st2 = new SynchronizedThread(lock);
        st1.setName("1111111111");
        st2.setName("2222222222");
        st1.start();
        try {
            Thread.sleep(1000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        st2.start();
    }
}

查看線程狀態(tài):

Paste_Image.png

可以看到線程命是‘2222222222’的線程狀態(tài)是WAITING

最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

  • 第三章 Java內(nèi)存模型 3.1 Java內(nèi)存模型的基礎 通信在共享內(nèi)存的模型里,通過寫-讀內(nèi)存中的公共狀態(tài)進行隱...
    澤毛閱讀 4,502評論 2 21
  • 線程 線程是進程中的一個單一順序的執(zhí)行單元,也被稱為輕量進程(lightweight process)。線程有自己...
    代碼界的蕭敬騰閱讀 1,259評論 0 0
  • 線程 線程是進程中的一個單一順序的執(zhí)行單元,也被稱為輕量進程(lightweight process)。線程有自己...
    代碼界的掃地僧閱讀 323評論 0 1
  • 下面是我自己收集整理的Java線程相關的面試題,可以用它來好好準備面試。 參考文檔:-《Java核心技術 卷一》-...
    阿呆變Geek閱讀 15,138評論 14 507
  • 今天1萬字的任務是絕對完成不了了。 我現(xiàn)在雖然在鍛煉,已經(jīng)半個小時多了,才走了三公里。 跟我的期望是完全不相符的,...
    圈圈o0閱讀 173評論 1 0

友情鏈接更多精彩內(nèi)容