A simple introduction to producer and consumer models:
The producer thread produces the item and then places the item in an empty buffer for consumption by the consumer thread. The consumer thread obtains the item from the buffer and then releases the buffer. When a producer thread produces an item, if no empty buffers are available, the producer thread must wait for the consumer thread to release an empty buffer. When consumer threads consume items, if there is no full buffer, then the consumer thread will be blocked until the new
public class Produceconsumer {public static void main (string[] args) {syncstack ss = new Syncstack (); Producer Pro = new Producer (ss); Consumer con = new Consumer (ss); new Thread (PRO). Start (); new Thread (Con). Start ();}} Class Product{int id;public Product (int id) {this.id = ID;} Public String toString () {return "Product:" +id;}} Class Syncstack{int index = 0; product[] Arrpro = new Product[6];p ublic synchronized void push (Product p) {while (index = = arrpro.length) {try {this.wait () ;} catch (Interruptedexception e) {e.printstacktrace ();}} This.notify (); Arrpro[index] = p;index++;} Public synchronized Product POPs () {while (index = = 0) {try {this.wait ();} catch (Interruptedexception e) {E.printstacktrace ();}} This.notify (); Index--;return arrpro[index];}} Class Producer implements Runnable{syncstack SS = Null;public Producer (syncstack ss) {THIS.SS = SS;} public void Run () {for (int i=0; i<20; i++) {Product p = new Product (i); Ss.push (P); System.out.println ("produced:" +p); try {thread.sleep);} catch (InterruptedexceptIon e) {e.printstacktrace ();}}}} Class Consumer implements Runnable{syncstack SS = Null;public Consumer (syncstack ss) {THIS.SS = SS;} public void Run () {for (int i=0; i<20; i++) {Product p = ss.pop (); System.out.println ("Consumed:" +p), try {thread.sleep (+);} catch (Interruptedexception e) {e.printstacktrace ();}}}}
The goods were produced.
Producer Consumer thread synchronization