在Java多線程編程中,wait()的作用的是讓當前線程進入阻塞狀態,notify()是讓當前線程喚醒繼續執行。雖然是對線程狀態的控制,但它們其實都是Object中的方法,這是因為wait與notify所起的作用與線程間的互斥鎖有關。
在執行wait()和notify()之前,必須要先獲得互斥鎖,即一定要和synchronized一起使用。wait()的含義是讓出獲得的互斥鎖,並讓自己進入阻塞狀態。在notify()的時候也已經獲得了互斥鎖,所做的事情就是喚醒當前線程繼續執行。
假如synchronized的鎖對象是obj的話,wait和notify正確的使用方法是obj.wait()和obj.notify()。如果使用this作為鎖,則可以直接寫成wait()和notify()。如果前後使用的鎖對象不一致,會發生IllegalMonitorStateException。
當有多個線程共同使用一個互斥鎖時,notify()會隨機選取一個執行過wait()的線程喚醒,其餘會繼續保持阻塞狀態。如果想喚醒所有阻塞的進程,就使用到了notifyAll()。
有點暈了麼,把代碼拿去執行可以好好體會下,一會看完代碼,看結論
| 代碼如下 |
複製代碼 |
package com.javaer.thread;
public class Twait {
public static void main(String[] args) {
TestThread testThread1 = new TestThread();
TestThread testThread2 = new TestThread();
TestThread testThread3 = new TestThread();
testThread1.start();
testThread2.start();
testThread3.start();
System.out.println("主線程休眠5秒");
try {
Thread.sleep(1000 * 5);
} catch (InterruptedException e) {
System.out.println("主線程 Interrupted");
}
System.out.println("喚醒 線程Thread-0");
testThread1.resumeByNotify();
try {
System.out.println("主線程再次休眠");
Thread.sleep(1000 * 5);
} catch (InterruptedException e) {
System.out.println("Main Thread Interrupted");
}
System.out.println("喚醒所有 By NotifyAll");
testThread1.resumeByNotifyAll();
}
}
class TestThread extends Thread {
private static Object obj = new Object();
@Override
public void run() {
System.out.println(getName() + " 即將進入阻塞");
synchronized (obj) {
try {
obj.wait();
} catch (InterruptedException e) {
System.out.println(getName() + " Test Thread Interrupted");
}
}
System.out.println(getName() + " 被喚醒");
}
public void resumeByNotify() {
synchronized (obj) {
obj.notify();
}
}
public void resumeByNotifyAll() {
synchronized (obj) {
obj.notifyAll();
}
}
}
|
Thread-0 即將進入阻塞
Thread-2 即將進入阻塞
主線程休眠5秒
Thread-1 即將進入阻塞
喚醒 線程Thread-0
主線程再次休眠
Thread-0 被喚醒
喚醒所有 By NotifyAll
Thread-1 被喚醒
Thread-2 被喚醒
上面的例子,子線程啟動了,就開始阻塞,然後主線程一個個的喚醒。沒有線程喚醒,這個子線程將一直等待。
testThread1.resumeByNotifyAll();
注釋這句話,程式將僵持在那裡。傳說中的殭屍。
Thread-0 即將進入阻塞
Thread-2 即將進入阻塞
主線程休眠5秒
Thread-1 即將進入阻塞
喚醒 線程Thread-0
主線程再次休眠
Thread-0 被喚醒
喚醒所有 By NotifyAll
到了這裡卡住了。
結論
1.wait 當前線程因為某種原因需要進入阻塞狀態,即線程暫停
2.notify 喚醒一個阻塞的線程即被wait的
3.notifyall 喚醒所有阻塞線程。
在調用wait的時候,線程自動釋放其佔有的對象鎖,同時不會去申請對象鎖。當線程被喚醒的時候,它才再次獲得了去獲得對象鎖的權利。