Condition the object Monitor method (wait, notify, and Notifyall) into distinct objects to provide multiple wait set (Wait-set) for each object by combining these objects with any Lock implementation. Where Lock replaces the use of the Synchronized method and the statement, Condition replaces the use of the Object monitor method. Today we use examples to learn the use of a condition.
Simple use of condition in multi-threading
I. Examples of water intake
- Boundedbuffer: Water can be installed without water, but not water, when the water is full, it can not be filled with water but to take water.
Importjava.util.concurrent.locks.Condition;ImportJava.util.concurrent.locks.Lock;ImportJava.util.concurrent.locks.ReentrantLock;classBoundedbuffer {FinalLock lock =NewReentrantlock (); FinalCondition Notfull =lock.newcondition (); FinalCondition Notempty =lock.newcondition (); Finalstring[] Items =NewString[10]; intputptr, Takeptr, Count; Public voidPut (String x)throwsinterruptedexception {lock.lock (); Try { while(Count = =items.length) notfull.await (); ITEMS[PUTPTR]=x; if(++putptr = = items.length) putptr = 0; ++count; Notempty.signal (); } finally{lock.unlock (); } } PublicString Take ()throwsinterruptedexception {lock.lock (); Try { while(count = = 0) notempty.await (); String x=Items[takeptr]; if(++takeptr = = items.length) takeptr = 0; --count; Notfull.signal (); returnx; } finally{lock.unlock (); } }}
- ConditionTest1: Open two threads, 20 times for water intake and water handling.
Public classConditionTest1 { Public Static voidMain (string[] args)throwsException {FinalBoundedbuffer Boundedbuffer =NewBoundedbuffer (); NewThread (NewRunnable () {@Override Public voidrun () { for(inti = 0; I < 20; i++) { Try{boundedbuffer.take (); System.out.print ("T" + i + ""); } Catch(interruptedexception e) {e.printstacktrace (); }}}). Start (); NewThread (NewRunnable () {@Override Public voidrun () { for(inti = 0; I < 20; i++) { Try{boundedbuffer.put ("String" +i); System.out.print ("P" + i + ""); } Catch(interruptedexception e) {e.printstacktrace (); }}}). Start (); }}
The results of the operation are as follows: not fixed
Friendship Link
- A Better Reference blog: http://www.cnblogs.com/lcngu/p/5208465.html
The use of the Java advanced---->thread condition