1. 程式人生 > >JAVA的wait和notify和notifyall

JAVA的wait和notify和notifyall

這個內容真是常學常忘啊,這次學了總結一下先:

一、wait、notify和notifyall一定要在synchronized語句塊中執行,並且synchronized的物件就是呼叫wait、notify和notifyall方法的物件。比如說下面這一對就會拋錯IllegalMonitorStateException:

                synchronized (testObj) {
                    widgets.notify();
                }

        synchronized (testObj) {
                try {
                    widgets.wait();
                } catch (InterruptedException e) {
                }
        }

必須是:

                synchronized (widgets) {
                    widgets.notify();
                }

        synchronized (widgets) {
                try {
                    widgets.wait();
                } catch (InterruptedException e) {
                }
        }


二、用什麼物件呼叫wait,就需要用同樣的物件呼叫notify。

三、多個執行緒使用同一個物件wait了以後,這些執行緒都停了,給出去了鎖。有鎖的那個執行緒呼叫一下notify,會隨機啟用一個剛才用這個物件停了的執行緒,用別的物件啟用的,不算。所以下面這道題,看看選啥:

How can you specify which thread is notified with the wait/notify protocol?
A:    Pass the object reference as a parameter to the notify method
B:    Pass the method name as a parameter to the notify method
C:    Use the notifyAll method and pass the object reference as a parameter
D:    The wait/notify protocol does not offer a method of specifying which thread will be notified.

四、如果是用notifyall,那所有使用這個物件停了的執行緒都被激活了,都去搶鎖了。例子可參考下面這個:

http://hi.baidu.com/scuyangl/item/5ca7dc255feaa10176272cca