sleep和wait方法區(qū)別懒豹,你真的知道了嗎?

更新時間:2018-03-12
大家都知道sleep方法是Thread中的驯用,wait方法來自于Object脸秽。但是調(diào)用了sleep和wait方法以后,線程處于什么狀態(tài)蝴乔?這里记餐,我們從jdk源碼開始分析。版本是oracle jdk 1.7薇正。

這里是sleep方法的源碼:上面有一句:The thread does not lose ownership of any monitors.翻譯過來就是不會放棄monitor對象,即不會放棄鎖挖腰;

    /**
     * Causes the currently executing thread to sleep (temporarily cease
     * execution) for the specified number of milliseconds, subject to
     * the precision and accuracy of system timers and schedulers. The thread
     * does not lose ownership of any monitors.
     *
     * @param  millis
     *         the length of time to sleep in milliseconds
     *
     * @throws  IllegalArgumentException
     *          if the value of {@code millis} is negative
     *
     * @throws  InterruptedException
     *          if any thread has interrupted the current thread. The
     *          <i>interrupted status</i> of the current thread is
     *          cleared when this exception is thrown.
     */
    public static native void sleep(long millis) throws InterruptedException;

這里看到的是wait方法的說明雕沿,會釋鎖資源等待喚。

  /**
     * Causes the current thread to wait until another thread invokes the
     * {@link java.lang.Object#notify()} method or the
     * {@link java.lang.Object#notifyAll()} method for this object.
     * In other words, this method behaves exactly as if it simply
     * performs the call {@code wait(0)}.
     * <p>
     * The current thread must own this object's monitor. The thread
     * releases ownership of this monitor and waits until another thread
     * notifies threads waiting on this object's monitor to wake up
     * either through a call to the {@code notify} method or the
     * {@code notifyAll} method. The thread then waits until it can
     * re-obtain ownership of the monitor and resumes execution.
     * <p>
     * As in the one argument version, interrupts and spurious wakeups are
     * possible, and this method should always be used in a loop:
     * <pre>
     *     synchronized (obj) {
     *         while (&lt;condition does not hold&gt;)
     *             obj.wait();
     *         ... // Perform action appropriate to condition
     *     }
     * </pre>
     * This method should only be called by a thread that is the owner
     * of this object's monitor. See the {@code notify} method for a
     * description of the ways in which a thread can become the owner of
     * a monitor.
     *
     * @exception  IllegalMonitorStateException  if the current thread is not
     *               the owner of the object's monitor.
     * @exception  InterruptedException if any thread interrupted the
     *             current thread before or while the current thread
     *             was waiting for a notification.  The <i>interrupted
     *             status</i> of the current thread is cleared when
     *             this exception is thrown.
     * @see        java.lang.Object#notify()
     * @see        java.lang.Object#notifyAll()
     */
    public final void wait() throws InterruptedException {
        wait(0);
    }

然后我們再看看Thread都有哪些狀態(tài)呢猴仑?NEW, RUNNABLE,BLOCKED,WAITING,TIMED_WAITING,TERMINATED;
一共6個狀態(tài)审轮,可以明顯看到,當(dāng)代碼塊遇到synchronize修飾時會轉(zhuǎn)換成狀態(tài):BLOCKED。當(dāng)調(diào)用wait()與join()方法時會變成狀態(tài):WAITING断国;當(dāng)調(diào)用wait(long)贤姆、join(long)、Thread.sleep方法時狀態(tài)為:TIMED_WAITING稳衬。

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;
    }

所以霞捡,sleep和wait方法有什么區(qū)別呢?總結(jié)下:
1.sleep方法是Thread中的薄疚,wait方法來自于Object碧信;
2.當(dāng)調(diào)用wait()方法時進(jìn)入WAITING狀態(tài),調(diào)用wait(long)和sleep方法時街夭,都可以進(jìn)入TIMED_WAITING狀態(tài)砰碴;
3.wait調(diào)用后需要被其他線程喚醒(notify/notifyAll);
4.sleep方法調(diào)用后不會放棄cpu資源板丽,而wait方法放棄鎖并在下次得到cpu資源才能繼續(xù)運(yùn)行呈枉;

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市埃碱,隨后出現(xiàn)的幾起案子猖辫,更是在濱河造成了極大的恐慌,老刑警劉巖砚殿,帶你破解...
    沈念sama閱讀 218,386評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件啃憎,死亡現(xiàn)場離奇詭異,居然都是意外死亡似炎,警方通過查閱死者的電腦和手機(jī)辛萍,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,142評論 3 394
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來羡藐,“玉大人贩毕,你說我怎么就攤上這事∑袜拢” “怎么了辉阶?”我有些...
    開封第一講書人閱讀 164,704評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長欧啤。 經(jīng)常有香客問我,道長启上,這世上最難降的妖魔是什么邢隧? 我笑而不...
    開封第一講書人閱讀 58,702評論 1 294
  • 正文 為了忘掉前任,我火速辦了婚禮冈在,結(jié)果婚禮上倒慧,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好纫谅,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,716評論 6 392
  • 文/花漫 我一把揭開白布炫贤。 她就那樣靜靜地躺著,像睡著了一般付秕。 火紅的嫁衣襯著肌膚如雪兰珍。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,573評論 1 305
  • 那天询吴,我揣著相機(jī)與錄音掠河,去河邊找鬼。 笑死猛计,一個胖子當(dāng)著我的面吹牛唠摹,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播奉瘤,決...
    沈念sama閱讀 40,314評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼勾拉,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了盗温?” 一聲冷哼從身側(cè)響起藕赞,我...
    開封第一講書人閱讀 39,230評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎肌访,沒想到半個月后找默,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,680評論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡吼驶,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,873評論 3 336
  • 正文 我和宋清朗相戀三年惩激,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片蟹演。...
    茶點(diǎn)故事閱讀 39,991評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡风钻,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出酒请,到底是詐尸還是另有隱情骡技,我是刑警寧澤,帶...
    沈念sama閱讀 35,706評論 5 346
  • 正文 年R本政府宣布羞反,位于F島的核電站布朦,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏昼窗。R本人自食惡果不足惜是趴,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,329評論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望澄惊。 院中可真熱鬧唆途,春花似錦富雅、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,910評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至温赔,卻和暖如春蛤奢,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背让腹。 一陣腳步聲響...
    開封第一講書人閱讀 33,038評論 1 270
  • 我被黑心中介騙來泰國打工远剩, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人骇窍。 一個月前我還...
    沈念sama閱讀 48,158評論 3 370
  • 正文 我出身青樓瓜晤,卻偏偏與公主長得像,于是被迫代替她去往敵國和親腹纳。 傳聞我的和親對象是個殘疾皇子痢掠,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,941評論 2 355

推薦閱讀更多精彩內(nèi)容