java sleep() 和 wait()有什麼區別呢?網友7941e35 2017-10-31

對於sleep()方法,我們首先要知道該方法是屬於Thread類中的。而wait()方法,則是屬於Object類中的。

sleep()方法導致了程式暫停執行指定的時間,讓出cpu該其他執行緒,但是他的監控狀態依然保持者,當指定的時間到了又會自動恢復執行狀態。

在呼叫sleep()方法的過程中,執行緒不會釋放物件鎖。

而當呼叫wait()方法的時候,執行緒會放棄物件鎖,進入等待此物件的等待鎖定池,只有針對此物件呼叫notify()方法後本執行緒才進入物件鎖定池準備

獲取物件鎖進入執行狀態。

什麼意思呢?

舉個列子說明:

/**

*

*/

package com。b510。test;

/**

* java中的sleep()和wait()的區別

* @author Java團長

* @date 2017-10-31

*/

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

public void 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!!!

且程式一直處於掛起狀態。

我有一個微信公眾號,經常會分享一些Java技術相關的乾貨,還有一些學習資源。

如果你喜歡我的分享,可以用微信搜尋“Java團長”或者“javatuanzhang”關注。

java sleep() 和 wait()有什麼區別呢?劇穎卿愚胭 2019-01-14

sleep是睡眠幾多少時間會自動再次執行,wait是等待別人,別人執行好了自己就可以執行,一般為協助時才用