java中wait、notify和notifyAll的概念用法和例子?
wait()、notify()和notifyAll()方法
新手不必過認真研究,有興趣的可研究
這三個方法僅在 synchronized 方法中才能被調(diào)用。
wait()方法告知被調(diào)用的線程退出監(jiān)視器馬克-to-win并進入等待狀態(tài),直到其他線程進入相同的監(jiān)視器并調(diào)用 notify( ) 方法。
notify( ) 方法通知同一對象上某一個調(diào)用 wait( )線程。 If any threads are waiting on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the discretion of the implementation.
notifyAll() 方法通知調(diào)用 wait() 的所有線程,競爭勝利的線程將先運行。 The awakened threads will compete in the usual manner with any other threads that might be actively competing to synchronize on this object; the awakened threads enjoy no reliable privilege or disadvantage in being the next thread to lock this object。
結(jié)論:notifyall是競爭,而notify是由具體實施的jvm決定的。
見下例:
例1.11.1-本章源碼
class DishMark_to_win {
private String food = "";
public synchronized String eat() {
try {
System.out.println("需要等一會,暫時無飯");
/* 當執(zhí)行下面的wait,這個線程將會暫停在這,然后當下列serve執(zhí)行notify,然后這個線程將從這繼續(xù)執(zhí)行。*/
wait();
System.out.println("接到通知可以了");
} catch (InterruptedException e) {
}
return food;
}
public synchronized void serve(String f) {
this.food = f;
/*下面二者都行*/
notify();
// notifyAll();
System.out.println("notify本身并不會釋放同步鎖,synchronized塊兒完了,才會釋放鎖");
try {
Thread.sleep(9000);
} catch (Exception e) {
}
System.out.println("等我歇9秒,synchronized塊兒完了,你才能獲得鎖,再給你端上去");
}
}
class Customer extends Thread {
private DishMark_to_win myDishMark_to_win;
public Customer(DishMark_to_win d) {
this.myDishMark_to_win = d;
}
public void run() {
System.out.println(myDishMark_to_win.eat());
}
}
class Restrant extends Thread {
private DishMark_to_win myDishMark_to_win;
public Restrant(DishMark_to_win d) {
this.myDishMark_to_win = d;
}
public void run() {
try {
Thread.sleep(4000);
} catch (Exception e) {
}
System.out.println("歇了4秒");
myDishMark_to_win.serve("魚香肉絲");
}
}
public class Test {
public static void main(String[] args) {
DishMark_to_win d = new DishMark_to_win();
Customer c = new Customer(d);
Restrant r = new Restrant(d);
c.start();
try {
Thread.sleep(100);
} catch (Exception e) {
}
r.start();
}
}
運行結(jié)果是
需要等一會,暫時無飯
歇了4秒
notify本身并不會釋放同步鎖,synchronized塊兒完了,才會釋放鎖
等我歇9秒,synchronized塊兒完了,你才能獲得鎖,再給你端上去
接到通知可以了
魚香肉絲