Condition:
- The condition interface describes the condition variables that may be related to locks. These usages are similar to using object.wait to access an implicit monitor, but provide more powerful functionality. It should be noted that a single lock may be associated with multiple condition objects. To avoid compatibility issues, the name of the condition method differs from the corresponding OBJEC version.
- In the condition object, the wait, notify, notifyall methods correspond to await, Singal, Signalall, respectively.
- The condition instance is essentially bound to a lock. To obtain an condition instance for a particular lock instance, use its newcondition () method.
Use lock to replace synchronized, use condition replace ojbect to implement inter-thread communication
Examples are as follows:
Package Com.dx.juc.test;import Java.util.concurrent.locks.condition;import java.util.concurrent.locks.Lock; Import Java.util.concurrent.locks.ReentrantLock; Public classLockandconditiontest { Public Static voidMain (string[] args) {Clerk Clerk=Newclerk (); Productor Productor=NewProductor (Clerk); Consumer Consumer=NewConsumer (Clerk); NewThread (Productor,"productor-a"). Start (); NewThread (Consumer,"consumer-a"). Start (); NewThread (Productor,"Productor-b"). Start (); NewThread (Consumer,"Consumer-b"). Start (); }}/** * Clerk*/classClerk {Private intProduct =0; PrivateLockLock=NewReentrantlock (); PrivateCondition Condition =Lock. Newcondition (); /** * Arrival*/ Public voidpurchase () {Lock.Lock(); Try { while(Product >=1) {System. out. println (Thread.CurrentThread (). GetName () +":"+"product is full ... "); Try{condition.await(); } Catch(interruptedexception e) {e.printstacktrace (); }} System. out. println (Thread.CurrentThread (). GetName () +":"+ ++product); Condition.signalall (); } finally { Lock. Unlock (); } } /** * Sell goods*/ Public voidSell () {Lock.Lock(); Try { while(Product <=0) {System. out. println (Thread.CurrentThread (). GetName () +":"+"Product shortage ... "); Try{condition.await(); } Catch(interruptedexception e) {e.printstacktrace (); }} System. out. println (Thread.CurrentThread (). GetName () +":"+ --product); Condition.signalall (); } finally { Lock. Unlock (); } }}/** * Producers continue to produce products to shop assistants*/classProductor implements Runnable {PrivateClerk Clerk; PublicProductor (Clerk clerk) { This. Clerk =clerk; } Public voidrun () { for(inti =0; I <2; i++) {clerk.purchase (); } }}/** consumers are constantly consuming products from shop assistants*/classConsumer implements Runnable {PrivateClerk Clerk; PublicConsumer (Clerk clerk) { This. Clerk =clerk; } Public voidrun () { for(inti =0; I <2; i++) {Clerk.sell (); } }}
Java-juc (ix): Use lock to replace synchronized, use condition's await,singal,singalall to replace the Wait,notify,notifyall of object for inter-thread communication