Java中wait()與sleep()的區別

來源:互聯網
上載者:User

標籤:

 類的區別
  • wait()來自於 java.lang.Object,任何對象都有此方法
  • sleep()來自於 java.lang.Thread,調用的對象為線程
用法上的區別

看一下jdk的描述:

wait():Causes the current thread to wait until either another thread invokes the
java.lang.Object.notify() method or the java.lang.Object.notifyAll()method for this object, or a specified amount of time has elapsed.

使當前線程掛起,當對象調用java.lang.Object.notify()或者java.lang.Object.notifyAll()或者時間到期,則從wait()中恢複執行

sleep():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.

在指定的時間內使當前執行的線程睡眠(暫停執行)

同步與鎖的不同

wait()與sleep()最主要的區別就在於同步與鎖,wiat()必須放在synchronized block中,否則會在program runtime時扔出java.lang.IllegalMonitorStateException異常。

  • wait()期間對象鎖是釋放的
  • 調用sleep()的時候鎖並沒有被釋放,調用yield()也屬於這種情況

    synchronized(LOCK) {       Thread.sleep(1000); // LOCK is held}synchronized(LOCK) {       LOCK.wait(); // LOCK is not held}

一般而言,wait()用於線程間的通訊,sleep()用於線程狀態的控制

參考資料

http://stackoverflow.com/questions/1036754/difference-between-wait-and...
http://howtodoinjava.com/2013/03/08/difference-between-sleep-and-wait/
http://www.qat.com/using-waitnotify-instead-thread-sleep-java/

Java中wait()與sleep()的區別

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.