I want to have a thread that sits on top of an event queue and reacts to it accordingly. My idea 开发者_运维问答was to have it clear all the elements, and once it reaches the end of the queue, hit wait()
until something notify()
's it. However, then the question is, what happens when the notify()
happens when the thread is not waiting?
P.S.: What's this monitor business I keep reading about in the javadoc?
The short answer is that nothing happens.
The slightly long answer is that if there is nothing waiting on the monitor, there is nothing for the notification to be delivered to, and the notification is silently discarded.
The monitor that you keep hearing about is just a technical term for the primitive locking mechanism that you are using. (IIRC the term was coined by the inventor of the monitor concept - Tony Hoare - who did a lot of the seminal work on concurrency.)
The idea is that there certain regions of code (in Java, they are synchronized method bodies and synchronized blocks) which a thread can only execute if it holds an exclusive lock. Other threads wanting to enter these regions have to wait for the lock to become available. The wait
and notify
methods provide an additional signalling mechanism that is used in conjunction with monitors.
It is not required that some thread be executing the wait() method when another thread calls the notify() method.Since the wait-and-notify mechanism does not know the condition about which it is sending notification, it assumes that a notification goes unheard if no thread is waiting.
In other words, if the notify() method is called when no other thread is waiting, notify() simply returns and the notification is lost. A thread that later executes the wait() method has to wait for another notification to occur.
In answer to your PS, monitors are one of the basic concurrency primitives. There are a few different flavors of them, of which Java uses the wait and notify variant. All this is well explained in the Wikipedia article:
http://en.wikipedia.org/wiki/Monitor_(synchronization)
精彩评论