Java------Multithreading: producers and consumers

Source: Internet
Author: User

The problem of producer and consumer is the classic problem of multithreading communication. Such problems describe a situation in which a warehouse is used to store products, producers are responsible for producing products, and consumers are responsible for consumption. Producers produce products that are stored in warehouses, and consumers take out products from warehouses. Obviously this is a synchronization issue, where producers and consumers share the same resources, and the producers and consumers depend on each other and move forward with each other. So how do you write code to implement it?


Class Resource {private String Name;private string sex;private Boolean flag = false;public synchronized void set (String na Me, String Sex) {if (flag = = True) {try {wait ();} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.prin Tstacktrace ();}} THIS.name = name + "--" + sex; System.out.println (Thread.CurrentThread (). GetName () + "--producer--" + this.name); flag = True;notify ();} Public synchronized void out () {if (flag = = False) {try {wait ()} catch (Interruptedexception e) {//TODO auto-generated C Atch blocke.printstacktrace ();}} System.out.println (Thread.CurrentThread (). GetName () + "---consumer---" + this.name); flag = False;notify ();}} Class Producer implements Runnable {private Resource resource;private int num = 0; Producer (Resource Resource) {this.resource = Resource;} public void Run () {while (true) {if (num = = 1) {Resource.set ("Lili", "female Female"),} else {Resource.set ("Mike", "Man");} num = ++num% 2;}}} Class Consumer implements Runnable {private Resource Resource; Consumer (Resource Resource) {this.resource = resource;} public void Run () {while (true) {Resource.out ()}}} Class Communicate {public static void main (string[] args) {Resource Resource = new Resource (); Producer Pro = new Producer (Resource); Consumer con = new Consumer (Resource); thread T1 = new Thread (PRO); Thread t2 = new Thread (con); T1.start (); T2.start ();}}

This example has been implemented in the production of one on the consumption of one, in fact, this example is the example in the previous article, just slightly optimize the code.

But there is a problem, this example is just a thread for production, a thread to spend, then how many more threads?


Let's add a few more threads to try.



Class Resource {private String Name;private string sex;private Boolean flag = false;public synchronized void set (String na Me, String Sex) {if (flag = = True) {try {wait ();} catch (Interruptedexception e) {//TODO auto-generated catch Blocke.prin Tstacktrace ();}} THIS.name = name + "--" + sex; System.out.println (Thread.CurrentThread (). GetName () + "--producer--" + this.name); flag = True;notify ();} Public synchronized void out () {if (flag = = False) {try {wait ()} catch (Interruptedexception e) {//TODO auto-generated C Atch blocke.printstacktrace ();}} System.out.println (Thread.CurrentThread (). GetName () + "---consumer---" + this.name); flag = False;notify ();}} Class Producer implements Runnable {private Resource resource;private int num = 0; Producer (Resource Resource) {this.resource = Resource;} public void Run () {while (true) {if (num = = 1) {Resource.set ("Lili", "female Female"),} else {Resource.set ("Mike", "Man");} num = ++num% 2;}}} Class Consumer implements Runnable {private Resource Resource; Consumer (Resource Resource) {this.resource = resource;} public void Run () {while (true) {Resource.out ()}}} Class Communicate {public static void main (string[] args) {Resource Resource = new Resource (); Producer Pro = new Producer (Resource); Consumer con = new Consumer (Resource); thread T1 = new Thread (PRO); Thread t2 = new Thread (PRO); thread t3 = new Thread (con); thread T4 = new thread (con); T1.start (); T2.start (); T3.start (); T4.start ();}}

In the printed results we find that this is the case:

thread-1--producer--mike--man

thread-0--producer--mike--man

Thread-2---consumer---mike--man

It is also possible to produce one and consume two cases. The reason for this is that the wait () is not too much to explain.

It is only necessary to change the if of the flag and then change the Notify to Notifyall () to OK.

The following modifications are completed:


Class Resource {private String Name;private string sex;private Boolean flag = false;public synchronized void set (String na Me, String Sex) {while (flag = = True) {try {wait ();} catch (Interruptedexception e) {//TODO auto-generated catch BLOCKE.P Rintstacktrace ();}} THIS.name = name + "--" + sex; System.out.println (Thread.CurrentThread (). GetName () + "--producer--" + this.name); flag = True;notifyall ();} Public synchronized void out () {while (flag = = False) {try {wait ();} catch (Interruptedexception e) {//TODO auto-generate D catch Blocke.printstacktrace ();}} System.out.println (Thread.CurrentThread (). GetName () + "---consumer---" + this.name); flag = False;notifyall ();}} Class Producer implements Runnable {private Resource resource;private int num = 0; Producer (Resource Resource) {this.resource = Resource;} public void Run () {while (true) {if (num = = 1) {Resource.set ("Lili", "female Female"),} else {Resource.set ("Mike", "Man");} num = ++num% 2;}}} Class Consumer implements Runnable {private Resource Resource; Consumer (ResourCE resource) {this.resource = resource;} public void Run () {while (true) {Resource.out ()}}} Class Communicate {public static void main (string[] args) {Resource Resource = new Resource (); Producer Pro = new Producer (Resource); Consumer con = new Consumer (Resource); thread T1 = new Thread (PRO); Thread t2 = new Thread (PRO); thread t3 = new Thread (con); thread T4 = new thread (con); T1.start (); T2.start (); T3.start (); T4.start ();}}






Java------Multithreading: producers and consumers

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.