I am very familiar with how the wait() / notify()
signaling scheme works in Java. However, I realized that the few usage patterns I've seen are variants of the Producer / Consumer scheme, or implementation of a Barrier . Also I have seen implementations of some well-known concurrent problems, such as the Dining Philosophers using wait/notify, but apparently for didactic purposes.
Moreover, all schemes followed the well-behaved recommendation of always invoking wait()
inside a loop, and only alter some shared variable after passing the loop, like the following code:
synchronized(mon) {
// #CP1 - Do not change variables here
while !(mycondition) {
try{
// #CP2 Do not change variables here
mon.wait();
} catch(catch (InterruptedException e) { e.printStackTrace(); }
}
// Condition satisfied - Now you can change!
makeOperation();
// Tell others that you're done and exit
mon.notifyAll();
}
My questions is: are there other patterns of usage of wait() / notify()
signaling than the ones I cited? Have you ever used it in an non-orthodox way? Why? Here are some more concrete questions to help:
#CP1
and #CP2
? notify()
instead of notifyAll()
? Though the possible performance gain, where you very sure about this wouldn't cause some dead-lock? Why? mycondition
depends on more than 1 thread, eg, mycondition= a_ready && b_ready && c_ready
?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.