Common sense, before some did not understand, resulting in writing code a lot of doubts.
In comparison with typical synchronization examples, two condition,notempty and notfull are used, corresponding to two lock,takelock and Putlock respectively. To view the code for take:
E x;
int c =-1;
Final Atomicinteger count = This.count;
Final Atomicinteger takelock = This.takelock;
Takelock.lockinterruptibly ();
try {
try {
while (count.get () = = 0) notempty.await ();
} catch (Interruptedexception IE) {
Notempty.signal ();
throw ie;
}
x = Extract ();
c = count.getanddecrement ();
if (C > 1) {
Notempty.signal ();
}
} finally {
Takelock.unlock ();
}
if (c = = capacity) {
Signalnotfull ();
}
return x;
Code in Singalnotfull:
Putlock.lock ();
try {notfull.signal ();} finally {Putlock.unlock ();}
Can be seen:
1.take operation may block, should allow terminal, so with lockinterruptably more friendly
2.for loop await is recommended by the Java documentation, and await success does not represent condition satisfaction, which is called pseudo-wakeup (spurious wakeup)
3.await () throw interruptedexception after signal let the next waiting thread pseudo-wake
4. Use signal instead of Signalall, wake up only one thread at a time, then find out and then signal again, wake up the next waiting thread, because condition is not necessarily able to get all the take threads to succeed when they are available (see if the queue size is not enough) So you don't have to Signalall
5. Using two locks, take Notempty (lock await) =>notfull (lock signal), put: Notfull (lock await) = Notempty (lock signal), So take and put can be the art of war, another problem is put in notfull lock after entering Await,block live, take thread will not get notfull lock signal and lead to deadlock? The answer is no, Because the await will release the lock first and then regain the lock after returning the money. In fact, the wait for object also has the same characteristics.
The locking mechanism in Linkedblockingqueue in JDK6