"JAVA" wait and notify usage, with production/consumption model

Source: Internet
Author: User

On the use of wait and notify, there have been a lot of detailed explanations on the internet, I just briefly summed up.

    1. Wait is used to release lock A and to block the thread where wait is Located. Unless the other thread holding lock a executes notify to wake up, it will be able to "live" Again.
    2. The notify is used to wake up threads that are blocked by waiting for lock a, so they are ready to compete for lock A. If more than one thread is blocked waiting for lock a, notify only wakes up one and wakes all with Notifyall.
    3. It is helpful to understand wait and notify by referring to the thread state diagram below.

Summarize:

    • Wait and notify are usually used with synchronized (obj), noting that obj should be the same object that is common for multithreading (that is, threads are competing for this object lock in a multithreaded state), and if they are not the same object, they cannot control concurrency. Wait and notify do not interact effectively because they are not manipulating the same object at All. You can refer to the demo sample at the end of the Article.
    • Wait and notify come from obj in synchronized, not elsewhere, and obj is just an object lock for each thread to Compete.

--------------------------------

Thread state diagram (the same thing, just in Chinese and english):

--------------------------------

Last Production/consumption model Code:

Base class

1  public Abstract classPersonImplementsrunnable{2 3      public StaticObject lock =NewObject ();4      public Static intTicket = 0;5 6      public Abstract voidExecute ();7}
View Code

---

Producers

1  public classProducerextendsperson {2 @Override3      public voidExecute () {4         synchronized(lock) {5              while(true){6                 if(ticket = = 0) {7                      while(ticket<10) {8System.out.println ("in production, Current quantity:" +ticket);9ticket++;Ten                         Try { oneThread.Sleep (1000); a}Catch(interruptedexception E) { - e.printstacktrace (); -                         } the                     } -System.out.println ("production completed, Current quantity:" +ticket); - lock.notify (); -}Else{ +                     Try { - lock.wait (); +}Catch(interruptedexception E) { a e.printstacktrace (); at                     } -                 } -             } -         } -     } -  in @Override -      public voidRun () { to Execute (); +     } -}
View Code

---

Consumers

1  public classConsumerextendsperson {2 @Override3      public voidExecute () {4         synchronized(lock) {5              while(true){6                 if(ticket==0){7                     Try {8 lock.wait ();9}Catch(interruptedexception E) {Ten e.printstacktrace (); one                     } a}Else{ -System.out.println ("total quantity in consumption:" +ticket); -                      while(ticket>0){ theSystem.out.println ("in consumption, Current quantity:" +ticket); -ticket--; -                         Try { -Thread.Sleep (1000); +}Catch(interruptedexception E) { - e.printstacktrace (); +                         } a                     } atSystem.out.println ("consumption completed, Current quantity:" +ticket); - lock.notify (); -                 } -             } -         } -     } in  - @Override to      public voidRun () { + Execute (); -     } the}
View Code

---

Run Demo

1  public classDemo {2 3      public Static voidmain (string[] Args) {4 5         //set the first production or first consumption, the default ticket is 0 production First. 6         //ticket is static, so it can be set, though not very canonical. 7         NewProducer (). ticket = 6;8 9Thread Pro =NewThread (NewProducer ());TenThread con =NewThread (NewConsumer ()); one Pro.start (); a Con.start (); -     } -}
View Code

Important thing to mention Again:

Summarize:

    • Wait and notify are usually used with synchronized (obj), noting that obj should be the same object that is common for multithreading (that is, threads are competing for this object lock in a multithreaded state), and if they are not the same object, they cannot control concurrency. Wait and notify do not interact effectively because they are not manipulating the same object at All. You can refer to the demo sample at the end of the Article.
    • Wait and notify come from obj in synchronized, not elsewhere, and obj is just an object lock for each thread to Compete.

-----------------------------------------------------

Please respect the results of the work of the author

Reprint Please specify source: http://www.cnblogs.com/ryanyu/p/6647238.html

"JAVA" wait and notify usage, with production/consumption model

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.