Java Multithreading--Condition control thread communication

Source: Internet
Author: User

The API documentation is so defined:

ConditionThe Object monitor methods ( wait , notify and notifyAll ) are decomposed into distinct objects so that they can be combined with any Lock implementation, Provides multiple wait set (Wait-set) for each object. This replaces the use of Lock synchronized methods and statements, Condition replacing the use of the Object monitor method.

The Condition interface describes the condition variables that may be associated with a lock . These variables are similar in usage to implicit monitors that use object.wait access, 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 Object version.
In the Condition object, the wait, notify, and Notifyall methods correspond to await, signal, and 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.

API-related methods:

    1. void await () causes the current thread to wait until it receives a signal or is interrupted.
    2. A Boolean await (long time, Timeunit unit) causes the current thread to wait until it receives a signal, is interrupted, or arrives at a specified wait time.
    3. Long Awaitnanos causes the current thread to wait until it receives a signal, is interrupted, or arrives at a specified wait time.
    4. void awaituninterruptibly () causes the current thread to remain in a wait state until it receives a signal.
    5. A Boolean awaituntil (Date deadline) causes the current thread to wait until it receives a signal, is interrupted, or arrives at a specified deadline.
    6. void signal () wakes up a waiting thread.
    7. void Signalall () wakes all waiting threads.

For example:

 PackageCom.company;Importjava.util.concurrent.locks.Condition;ImportJava.util.concurrent.locks.Lock;ImportJava.util.concurrent.locks.ReentrantLock;/** Producer Consumer case:*/ Public classTestproductorandconsumerforlock { Public Static voidMain (string[] args) {Clerk Clerk=Newclerk (); Productor Pro=NewProductor (Clerk); Consumer Con=NewConsumer (Clerk); NewThread (Pro, "producer A"). Start (); NewThread (Con, "Consumer B"). Start ();//New Thread (Pro, "producer C"). Start ();//new Thread (Con, "Consumer D"). Start ();    }}classClerk {Private intProduct = 0; PrivateLock lock =NewReentrantlock (); PrivateCondition Condition =lock.newcondition (); //Arrival     Public voidget () {lock.lock (); Try {            if(Product >= 1) {//In order to avoid false wakes, it should always be used in loops. SYSTEM.OUT.PRINTLN ("The product is full! "); Try{condition.await ();//alternative this.wait;}Catch(Interruptedexception e) {}} System.out.println (Thread.CurrentThread (). GetName ()+ " : "                    + ++product); Condition.signalall ();//instead of This.notifyall ();}finally{lock.unlock (); }    }    //Sell Goods     Public voidSale () {lock.lock (); Try {            if(Product <= 0) {System.out.println (Stock "); Try{condition.await ();//alternative this.wait;}Catch(Interruptedexception e) {}} System.out.println (Thread.CurrentThread (). GetName ()+ " : "                    + --product); Condition.signalall ();//instead of This.notifyall ();        } finally{lock.unlock (); }    }}//producersclassProductorImplementsRunnable {PrivateClerk Clerk;  PublicProductor (Clerk clerk) { This. Clerk =clerk; } @Override Public voidrun () { for(inti = 0; I < 20; i++) {            Try{Thread.Sleep (200); } Catch(interruptedexception e) {e.printstacktrace ();        } clerk.get (); }    }}//ConsumerclassConsumerImplementsRunnable {PrivateClerk Clerk;  PublicConsumer (Clerk clerk) { This. Clerk =clerk; } @Override Public voidrun () { for(inti = 0; I < 20; i++) {Clerk.sale (); }    }}

Results:

Out of stock! Producer A:1Consumer B:0Out of stock! Producer A:1Consumer B:0Out of stock! Producer A:1Consumer B:0Out of stock! Producer A:1Consumer B:0Out of stock! Producer A:1Consumer B:0Out of stock! Producer A:1Consumer B:0Out of stock! Producer A:1Consumer B:0Out of stock! Producer A:1Consumer B:0Out of stock! Producer A:1Consumer B:0Out of stock! Producer A:1Consumer B:0Out of stock! Producer A:1Consumer B:0Out of stock! Producer A:1Consumer B:0Out of stock! Producer A:1Consumer B:0Out of stock! Producer A:1Consumer B:0Out of stock! Producer A:1Consumer B:0Out of stock! Producer A:1Consumer B:0Out of stock! Producer A:1Consumer B:0Out of stock! Producer A:1Consumer B:0Out of stock! Producer A:1Consumer B:0Out of stock! Producer A:1Consumer B:0

Java Multithreading--Condition control thread communication

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.