Using condition to control thread communication in Java (Java Madness Handout)

Source: Internet
Author: User

If the program does not use the Synchronized keyword to guarantee synchronization, but instead uses the lock object directly to ensure synchronization, there is no implicit synchronization monitor in the system, and you cannot communicate using the Wait (), notify (), Notifyall () methods.

When using the lock object to ensure synchronization, Java provides a condition class to maintain coordination, and the condition can be used to release the lock object for those threads that have already obtained the lock object but cannot continue to execute. The condition object can also wake other waiting threads.

Condition decomposes the synchronization monitor method (Wait (), notify (), and Notifyall ()) into distinct objects that provide multiple wait sets (Wait-set) for each object by combining these objects with the lock object. In this case, lock replaces the synchronization method or synchronization code block, and condition replaces the functionality of the synchronization monitor.

Condition instances are bound to a lock object, to obtain a condition instance of a particular lock instance, call the Newcondition () method of the lock object. The condition class provides the following 3 methods.

1.await (): Similar to the Wait () method on the implicit synchronization monitor, which causes the current thread to wait, knowing that other threads call the condition's signal () method or the Signalall () method to wake the thread, The await () method has more variants, such as Long Awaitnanos (long nanostimeout), void awaituninterruptibly (), Awaituntil (Data deadline), and so on. You can complete a rich wait operation.

2.signal (): wakes a single thread waiting on this lock object, and if all threads are waiting on the lock object, it will choose to wake one of the threads and choose to be arbitrary. The wake-up thread can only be executed if the front-thread discards the lock object (using the await () method).

3.Signalall (): wakes up all the threads waiting on this lock object, and only the thread that wakes up can be executed if the thread discards the lock on the object lock object.

1 Importjava.util.concurrent.locks.Condition;2 ImportJava.util.concurrent.locks.ReentrantLock;3  Public classconditionclass{4      Public Static voidMain (string[] args) {5Account A=NewAccount ("1", 100000);6ThreadClass t=NewThreadClass (a,1000, "NO1");7         NewThread (NewRunnableclass (a,500) . Start ();8         NewThread (NewRunnableclass (a,500) . Start ();9         NewThread (NewRunnableclass (a,500) . Start ();Ten     } One } A classaccount{ -     //display the defined lock object -     Private FinalReentrantlock lock=NewReentrantlock (); the     //gets the condition corresponding to the specified lock object -     Private FinalCondition cond=lock.newcondition (); -     PrivateString name; -     Private DoubleMoney ; +     Private Booleanflag=false; -      PublicAccount (String name,DoubleMoney ) { +          This. name=name; A          This. money=Money ; at     } -      Public DoubleGetmoney () { -         returnMoney ; -     } -      Public voidMakeDoubleDymoney) { - Lock.lock (); in         Try{ -             if(!flag) {       toSystem.out.println (Thread.CurrentThread (). GetName () + "stored:" +Dymoney); +money+=Dymoney; -System.out.println ("The Balance now is:" +Money ); theflag=true; * Cond.signalall (); $}Else{Panax Notoginseng cond.await (); -             } the}Catch(Exception e) {System.out.println (e);}finally{ + Lock.unlock (); A         } the     } +      Public voidTakeDoubleDymoney) { - Lock.lock (); $         Try{ $             if(flag) { -System.out.println (Thread.CurrentThread (). GetName () + "taken away:" +Dymoney); -money-=Dymoney; theflag=false; -System.out.println ("The Balance now is:" +Money );Wuyi Cond.signalall (); the}Else{ - cond.await (); Wu             } -}Catch(Exception e) { About System.out.println (e); $}finally{ - Lock.unlock (); -         } -     } A } + classThreadClassextendsthread{ the     PrivateAccount account ; -     Private DoubleDymoney; $     PrivateString name; the      PublicThreadClass (Account account,Doubledymoney,string name) { the         Super(name); the          This. account=Account ; the          This. dymoney=Dymoney; - start (); in     } the      Public voidrun () { the          for(inti=0;i<100;i++){ About Account.make (Dymoney); the         } the     } the      + } - classRunnableclassImplementsrunnable{ the     PrivateAccount account ;Bayi     Private DoubleDymoney; the      PublicRunnableclass (Account account,DoubleDymoney) { the          This. account=Account ; -          This. dymoney=Dymoney; -     } the      Public voidrun () { the          for(intk=0;k<100;k++){ the         Try{ theThread.Sleep (1000); - Account.take (Dymoney); the}Catch(Exception e) {} the         } the     }94}


The display uses the lock object to act as the synchronization monitor, you need to use the condition object to pause and wake the specified thread.

Using condition to control thread communication in Java (Java Madness Handout)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.