In the previous producer consumer program, the data produced by the producer at a time can be read multiple times by the consumer. Obviously, this does not meet our requirements. In this regard, the above procedures are improved:
1) The producer produces data once and the consumer obtains the data once;
2) A bucket can only store one pair of data
We will use the following code:
Java implements inter-thread communication through the wait \ Policy \ nopolicyall methods of the Object class.
Wait: tells the current thread to discard the monitor and go to sleep state. It knows that other threads enter the same monitor and calls y.
Wake Y: Wake up the first thread that calls wait in the same object monitor. It is used to notify the first Orthopedic Department to be seated after a restaurant has a vacant space.
Policyall:
Wake up all the threads that call wait in the same object Monitor, and the threads with the highest priority are first awakened and executed, for example, after an irregular training course is finally fully enrolled, notify all students of coming to class.
Wait \ Policy \ nopolicyall can only be called in the synchronized method, that is, the thread must first obtain the lock flag of this object.
Package day14;/*** data Storage area, and set the default production content ** @ author well **/class Storage {String name = "Tom "; string sex = "male";/*** status of the bucket. If no data exists, this parameter is set to false. If data exists, this parameter is set to true */boolean sFull = false; /*** put data ** @ param name * @ param sex */public synchronized void put (String name, String sex) {// wait for while (sFull) {try {wait ();} catch (InterruptedException e) {e. printStackTrace () ;}} this. name = name; try {Thread. sleep (10 );} Catch (InterruptedException e) {e. printStackTrace ();} this. sex = sex; sFull = true; // set the data zone to full when y (); // wake up the consumer process waiting for the queue}/*** fetch data */public synchronized void get () {while (! SFull) {try {wait ();} catch (InterruptedException e) {e. printStackTrace () ;}} System. out. println (name + "," + sex); sFull = false; // after the data is removed, set the data zone to blank notify (); // wake up the Producer process in the waiting queue}/*** Producer process ** @ author well **/class Producer implements Runnable {Storage s = null; Producer (Storage s) {super (); this. s = s ;}@ Overridepublic void run () {int I = 0; for (; I <500; I ++) {if (I % 2 = 0) {s. put ("Lily", "female");} else {s. put ("Tom", "male") ;}}}/*** Consumer process ** @ author well **/class Consumer implements Runnable {Storage s = null; consumer (Storage s) {super (); this. s = s ;}@ Overridepublic void run () {for (int I = 0; I <500; I ++) {s. get () ;}} public class PCDemo {public static void main (String [] args) {Storage s = new Storage (); new Thread (new Producer (s )). start (); new Thread (new Consumer (s )). start ();}}