對于sleep()方法,我們首先要知道該方法是屬于Thread類中的。而wait()方法,則是屬于Object類中的瞬逊。
sleep()方法導(dǎo)致了程序暫停執(zhí)行指定的時間,讓出cpu該其他線程仪或,但是他的監(jiān)控狀態(tài)依然保持者确镊,當(dāng)指定的時間到了又會自動恢復(fù)運行狀態(tài)。
在調(diào)用sleep()方法的過程中范删,線程不會釋放對象鎖蕾域。
而當(dāng)調(diào)用wait()方法的時候,線程會放棄對象鎖到旦,進入等待此對象的等待鎖定池旨巷,只有針對此對象調(diào)用notify()方法后本線程才進入對象鎖定池準(zhǔn)備
獲取對象鎖進入運行狀態(tài)。
什么意思呢添忘?
舉個列子說明:
/**
*
*/
package com.b510.test;
/**
* java中的sleep()和wait()的區(qū)別
*/
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 {
//調(diào)用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....");
//只有針對此對象調(diào)用notify()方法后本線程才進入對象鎖定池準(zhǔn)備獲取對象鎖進入運行狀態(tài)昔汉。
TestD.class.notify();
//==================
//區(qū)別
//如果我們把代碼:TestD.class.notify();給注釋掉懈万,即TestD.class調(diào)用了wait()方法,但是沒有調(diào)用notify()
//方法靶病,則線程永遠處于掛起狀態(tài)会通。
try {
//sleep()方法導(dǎo)致了程序暫停執(zhí)行指定的時間,讓出cpu該其他線程娄周,
//但是他的監(jiān)控狀態(tài)依然保持者涕侈,當(dāng)指定的時間到了又會自動恢復(fù)運行狀態(tài)。
//在調(diào)用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!!!
且程序一直處于掛起狀態(tài)。