Java implements producer consumers
<span style= "FONT-SIZE:18PX;" >package Com.clark.thread;public class Mantou {public int order;public Mantou (int order) {this.order = order;} @Overridepublic String toString () {return ' Mantou: ' +this.order;}} </span>
<span Style= "FONT-SIZE:18PX;" >package com.clark.thread;//Shared stack space public class Stackbasket {public mantou[] mt = new Mantou[10];int index = 0;//production steamed bun Publ IC synchronized void push (Mantou m) {try {while (index = = mt.length) {System.out.println ("Production full!!!!!!!"); This.wait ();} This.notify ();} catch (Interruptedexception e) {e.printstacktrace ();} mt[index]=m;index++; System.out.println ("produced:" + M + "Total" + index + "a steamed bun"); }//consumption synchronized Mantou pop () {try {while (index = = 0) {System.out.println ("consume, please wait!!!!"); This.wait ();} This.notify ();} catch (Exception e) {}index--; System.out.println ("Consumption:---------" + Mt[index] + "Total" + index + "a steamed bun"); return mt[index];}} </span>
<span style= "FONT-SIZE:18PX;" >package com.clark.thread;//producer public class Producer implements Runnable{stackbasket SB = new Stackbasket ();p ublic Producer (Stackbasket sb) {this.sb = SB;} @Overridepublic void Run () {for (int i = 0; I <8; i++) {Mantou m = new Mantou (i); Sb.push (m); try {thread.sleep (1);} CATC H (interruptedexception e) {e.printstacktrace ();}}}} </span>
<span style= "FONT-SIZE:18PX;" >package Com.clark.thread;public class Consumer implements Runnable{stackbasket SB = new Stackbasket ();p ublic Consumer (Stackbasket sb) {this.sb = SB;} @Overridepublic void Run () {for (int i = 0; I <8; i++) {Mantou m = Sb.pop (); try {thread.sleep (1);} catch (Interruptedex Ception e) {e.printstacktrace ();}}}} </span>
<span style= "FONT-SIZE:18PX;" >package Com.clark.thread;public class Test {public static void main (string[] args) {stackbasket sb = new Stackbasket () ; Producer p = new Producer (SB); Consumer C = new Consumer (SB); thread T1 = new Thread (p); Thread t2 = new Thread (c); T1.start (); T2.start ();}} </span>
Java Implementation producer consumer