Java Thread 的 sleep() 和 wait() 的區別


 

 

 
 

1. sleep 和 wait 方法解釋

sleep()方法是Thread類里面的,主要的意義就是讓當前線程停止執行,讓出cpu給其他的線程,但是不會釋放對象鎖資源以及監控的狀態,當指定的時間到了之后又會自動恢復運行狀態。

wait()方法是Object類里面的,主要的意義就是讓線程放棄當前的對象的鎖,進入等待此對象的等待鎖定池,只有針對此對象調動notify方法后本線程才能夠進入對象鎖定池准備獲取對象鎖進入運行狀態。

 

2. 實例

舉個列子說明:

 /** java中的sleep()和wait()的區別 */
public class TestD { public static void main(String[] args) { new Thread(new Thread1()).start(); try { Thread.sleep(5000); } catch (Exception e) { e.printStackTrace(); } new Thread(new Thread2()).start(); } private static class Thread1 implements Runnable{ @Override publicvoid run(){ synchronized (TestD.class) { System.out.println("enter thread1..."); System.out.println("thread1 is waiting..."); try { //調用wait()方法,線程會放棄對象鎖,進入等待此對象的等待鎖定池
                TestD.class.wait(); } catch (Exception e) { e.printStackTrace(); } System.out.println("thread1 is going on ...."); System.out.println("thread1 is over!!!"); } } } private static class Thread2 implements Runnable{ @Override public void run(){ synchronized (TestD.class) { System.out.println("enter thread2...."); System.out.println("thread2 is sleep...."); //只有針對此對象調用notify()方法后本線程才進入對象鎖定池准備獲取對象鎖進入運行狀態。
                 TestD.class.notify(); //================== //區別 //如果我們把代碼:TestD.class.notify();給注釋掉,即TestD.class調用了wait()方法,但是沒有調用notify() //方法,則線程永遠處於掛起狀態。
                try { //sleep()方法導致了程序暫停執行指定的時間,讓出cpu該其他線程, //但是他的監控狀態依然保持者,當指定的時間到了又會自動恢復運行狀態。 //在調用sleep()方法的過程中,線程不會釋放對象鎖。
                     Thread.sleep(5000); } catch (Exception e) { e.printStackTrace(); } System.out.println("thread2 is going on...."); System.out.println("thread2 is over!!!"); } } } }
運行效果:
enter thread1...
thread1 is waiting...
enter thread2....
thread2 is sleep....
thread2 is going on....
thread2 is over!!!
thread1 is going on ....
thread1 is over!!!

如果注釋掉代碼:

TestD.class.notify();

運行效果:

enter thread1...
thread1 is waiting...
enter thread2....
thread2 is sleep....
thread2 is going on....
thread2 is over!!!

相信看完例子應該就知道二者的區別了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM