Primary discussion of Java producers and consumers

Source: Internet
Author: User

Recently learning Java multithreading a little confused, after a day of finishing, know what is the producer, what is the consumer, as well as the relationship between consumers and producers:

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M00/6C/7E/wKiom1VKLYzRB5F-AAC5bQtmq-I129.jpg "title=" Producer consumer schematic. png "alt=" wkiom1vklyzrb5f-aac5bqtmq-i129.jpg "/>

In the person class is an entity does not have a specific object, by input, output readout, only if input has passed in, can be output read, so yes input and output, to the same lock, synchronized two threads synchronization.

Wait (), notify (), Notifyall () are all inherited to the God class: The following is the code of the producer consumer


  1. //Production/consumer mode

  2. Public class Basket {

  3. Lock lock = new reentrantlock ();

  4. //Generate Condition Object

  5. Condition produced = Lock.newcondition ();

  6. Condition consumed = Lock.newcondition ();

  7. Boolean available = false;

  8. Public void Produce () throws interruptedexception {

  9. Lock.lock ();

  10. Try {

  11. if (available) {

  12. Produced.await (); //Discard lock into sleep

  13. }

  14. System.out.println (" Apple produced.");

  15. Available = true;

  16. Consumed.signal (); //Signal wakeup wait for this condition thread

  17. } finally {

  18. Lock.unlock ();

  19. }

  20. }

  21. Public void consume () throws interruptedexception {

  22. Lock.lock ();

  23. Try {

  24. if (!available) {

  25. Consumed.await (); //Discard lock into sleep

  26. }

  27. / * Eat apples * /

  28. System.out.println (" Apple consumed.");

  29. Available = false;

  30. Produced.signal (); //Signal wakeup wait for this condition thread

  31. } finally {

  32. Lock.unlock ();

  33. }

  34. }

  35. }


This article from "Javase and Android" blog, declined reprint!

Primary discussion of Java producers and consumers

Related Article

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.