- sleep() 是 Thread 類的靜態本地方法;wait() 是Object類的成員本地方法
- sleep() 方法可以在任何地方使用;wait() 方法則只能在同步方法或同步代碼塊中使用,否則拋出異常Exception in thread "Thread-0" java.lang.IllegalMonitorStateException
- sleep() 會休眠當前線程指定時間,釋放 CPU 資源,不釋放對象鎖,休眠時間到自動蘇醒繼續執行;wait() 方法放棄持有的對象鎖,進入等待隊列,當該對象被調用 notify() / notifyAll() 方法后才有機會競爭獲取對象鎖,進入運行狀態
- JDK1.8 sleep() wait() 均需要捕獲 InterruptedException 異常
測試代碼
public class TestWaitSleep { private static Object obj = new Object(); public static void main(String[] args) { //測試sleep() //測試 RunnableImpl1 wait(); RunnableImpl2 notify() Thread t1 = new Thread(new RunnableImpl1(obj)); Thread t2 = new Thread(new RunnableImpl2(obj)); t1.start(); t2.start(); //測試RunnableImpl3 wait(long timeout)方法 Thread t3 = new Thread(new RunnableImpl3(obj)); t3.start(); } } class RunnableImpl1 implements Runnable { private Object obj; public RunnableImpl1(Object obj) { this.obj = obj; } public void run() { System.out.println("run on RunnableImpl1"); synchronized (obj) { System.out.println("obj to wait on RunnableImpl1"); try { obj.wait(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("obj continue to run on RunnableImpl1"); } } } class RunnableImpl2 implements Runnable { private Object obj; public RunnableImpl2(Object obj) { this.obj = obj; } public void run() { System.out.println("run on RunnableImpl2"); System.out.println("睡眠3秒..."); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (obj) { System.out.println("notify obj on RunnableImpl2"); obj.notify(); } } } class RunnableImpl3 implements Runnable { private Object obj; public RunnableImpl3(Object obj) { this.obj = obj; } public void run() { System.out.println("run on RunnableImpl3"); synchronized (obj) { System.out.println("obj to wait on RunnableImpl3"); try { obj.wait(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("obj continue to run on RunnableImpl3"); } } }
打印結果
run on RunnableImpl2
睡眠3秒...
run on RunnableImpl1
obj to wait on RunnableImpl1
run on RunnableImpl3
obj to wait on RunnableImpl3
obj continue to run on RunnableImpl3
notify obj on RunnableImpl2
obj continue to run on RunnableImpl1
- Java 自學指南
- Java 面試題匯總PC端瀏覽【點這里】
- Java知識圖譜
- Java 面試題匯總小程序瀏覽,掃二維碼
所有資源資源匯總於公眾號