為什么80%的碼農都做不了架構師?>>> ??
面試中常問的就是 sleep 和 wait 有什么不同嗎?為了面試時候發揮的更好,我在這里總結分享下。
首先對于 sleep() 方法,我們首先要知道該方法是屬于 Thread 類中的。而 wait() 方法,則是屬于Object類中的。(說完這句之后面試官會不會問你說下 object 類中的方法。。。哈哈哈)
最主要是 sleep 方法不會釋放對象鎖 ,而 wait 方法釋放對象鎖 。
sleep() 方法是線程類(Thread)的靜態方法,讓調用線程進入睡眠狀態,讓出執行機會給其他線程,等到休眠時間結束后,線程進入就緒狀態和其他線程一起競爭 cpu 的執行時間。
因為 sleep() 是 static 靜態的方法,他不能改變對象的機鎖,當一個 synchronized 塊中調用了 sleep() 方法,線程雖然進入休眠,但是對象的機鎖沒有被釋放,其他線程依然無法訪問這個對象。
當一個線程執行到 wait 方法時,它就進入到一個和該對象相關的等待池,同時釋放對象的機鎖,使得其他線程能夠訪問,可以通過 notify,notifyAll 方法來喚醒等待的線程。
package com.example.demo;public class T {public static void main(String[] args) {new Thread(new t1()).start();try {Thread.sleep(3000);} catch (InterruptedException e) {e.printStackTrace();}new Thread(new t2()).start();}private static class t1 implements Runnable {@Overridepublic void run() {synchronized (T.class) {System.out.println("start t1...");System.out.println("t1 wait...");try {// 調用 wait()方法,線程會放棄對象鎖,進入等待此對象的等待鎖定池T.class.wait();} catch (Exception e) {e.printStackTrace();}}System.out.println("t1 going on....");System.out.println("t1 over...");}}private static class t2 implements Runnable {@Overridepublic void run() {synchronized (T.class) {System.out.println("start t2...");System.out.println("t2 sleep...");// 只有針對此對象調用 notify()方法后本線程才進入對象鎖定池準備獲取對象鎖進入運行狀態。T.class.notify();try {// sleep()方法導致了程序暫停執行指定的時間,讓出cpu該其他線程,但是他的監控狀態依然保持者,當指定的時間到了又會自動恢復運行狀態。// 在調用 sleep()方法的過程中,線程不會釋放對象鎖。Thread.sleep(3000);} catch (Exception e) {e.printStackTrace();}System.out.println("t2 going on....");System.out.println("t2 over...");}}}
}
第一種情況結果,使用 wait 釋放鎖,并且喚醒等待線程。
第二種情況不喚醒等待線程,注釋掉
T.class.wait();
結果程序會一直掛起。
?
水平有限,若有問題請留言交流!
互相學習,共同進步:) 轉載請注明出處謝謝!