I. Overview
Simulating producer consumer issues
Second, the Code
1.consumer.java
2.producer.java
3.syncstack.java
4.test.java
1.consumer.java
Package Producerconsumer;public class Consumer implements Runnable {private Syncstack syncstack;public Consumer ( Syncstack syncstack) {super (); this.syncstack = Syncstack;} Public void Consume () {Product p, for (int i = 0; i <; i++) {p = Syncstack.pop (); SYSTEM.OUT.PRINTLN ("****** consumed:" +p);}} @Overridepublic void Run () {//try {//thread.sleep ()//} catch (Interruptedexception e) {//e.printstacktrace ();/} Consume ();}}
2.producer.java
Package Producerconsumer;public class Producer implements Runnable {private Syncstack syncstack;public Producer ( Syncstack syncstack) {super (); this.syncstack = Syncstack;} Public void Produce () {for (int i = 0; i < i++) {Product p = new product (i); Syncstack.push (P); System.out.println ("produced:" +p);}} @Overridepublic void Run () {produce ();}}
3.syncstack.java
Package Producerconsumer;import Java.util.arraylist;import Java.util.list;public class Syncstack {int index = 0; Product [] PS = new product[6];//list<product> PS = new arraylist<product> (); Public synchronized void push (Product p) {//if (index = = ps.length) {//cannot be determined with if, if the this.wait () exception occurs, The code will still be executed down while (index = = ps.length) {try {this.wait ()} catch (Interruptedexception e) {e.printstacktrace ()}} This.notifyall ();p S[index] = P;index = index + 1;//system.out.println (index);} Public synchronized Product POPs () {while (index = = 0) {try {this.wait ();} catch (Interruptedexception e) { E.printstacktrace ();}} This.notifyall (); index--;return ps[index];//system.out.println ("ps====" +ps);//product p = ps.get (Ps.size ()-1);// Ps.remove (Ps.size ()-1);//return p;}}
4.test.java
Package Producerconsumer;public class Test {public static void main (string[] args) {syncstack ss = new Syncstack (); Producer P1 = new Producer (ss); Consumer C1 = new Consumer (ss); Thread TP1 = new Thread (p1); Thread TC1 = new Thread (c1); Tc1.start (); Tp1.start (); new Thread (New Producer (ss)). Start (); New Thread (New Consumer (ss)). Start ();}}
Iii. Results of operation
Iv. Summary
1.this.wait (), which holds the lock before calling wait,wait, is the thread that is accessing this object, wait, and the lock on this thread is lost after wait, only when the thread wakes up to retrieve the lock. Sleep locks are not lost.
2.this.notify () wakes a thread on the current object that is being wait
JAVA-J2SE Learning Notes-threading-producer consumer issues