java中wait、notify和notifyAll的概念用法和例子?

wait()、notify()和notifyAll()方法
新手不必過(guò)認(rèn)真研究,有興趣的可研究

這三個(gè)方法僅在 synchronized 方法中才能被調(diào)用。

wait()方法告知被調(diào)用的線程退出監(jiān)視器馬克-to-win并進(jìn)入等待狀態(tài),直到其他線程進(jìn)入相同的監(jiān)視器并調(diào)用 notify( ) 方法。

notify( ) 方法通知同一對(duì)象上某一個(gè)調(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() 的所有線程,競(jìng)爭(zhēng)勝利的線程將先運(yùn)行。 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是競(jìng)爭(zhēng),而notify是由具體實(shí)施的jvm決定的。



見(jiàn)下例:





例1.11.1-本章源碼

class DishMark_to_win {
    private String food = "";
    public synchronized String eat() {
        try {
            System.out.println("需要等一會(huì),暫時(shí)無(wú)飯");
/* 當(dāng)執(zhí)行下面的wait,這個(gè)線程將會(huì)暫停在這,然后當(dāng)下列serve執(zhí)行notify,然后這個(gè)線程將從這繼續(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本身并不會(huì)釋放同步鎖,synchronized塊兒完了,才會(huì)釋放鎖");
        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("魚(yú)香肉絲");
    }
}

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();
    }
}

運(yùn)行結(jié)果是
需要等一會(huì),暫時(shí)無(wú)飯
歇了4秒
notify本身并不會(huì)釋放同步鎖,synchronized塊兒完了,才會(huì)釋放鎖
等我歇9秒,synchronized塊兒完了,你才能獲得鎖,再給你端上去
接到通知可以了
魚(yú)香肉絲