Http://www.cnblogs.com/zyp4614/p/6033757.html
(Java and operating system process synchronization problem (i) ———— mutex issues)
Today is the most classic producer of consumer problems, the simplest version, that is, only one buffer, the buffer can only put one item, that is, regardless of the mutual exclusion relationship.
Simple analysis: Producers can put products in buffers when the buffer is empty, consumers can take a product when the buffer is not empty (that is, when there is a product in the buffer).
First you can determine that there are two semaphores
The first semaphore is whether the buffer is empty, when the producer can put in the product, the initial value is 1, because the default buffer is empty
The second semaphore is whether the buffer is full, the consumer can take out the product when full, the initial value is 0, because there is no product in the start buffer
/** * Indicates whether the buffer is empty */ Semaphore empty; /** * Indicates whether the buffer is full */ Semaphore;
Producer pseudo code is as follows
Wait (empty) // Add Product signal (FULL)
The consumer pseudo-code is as follows:
Wait (full) // Fetch Products signal (empty)
Class is implemented as follows
Public classProductandvistor {Thread producer=NewThread (NewRunnable () {@Override Public voidrun () {String className= "Producer"; //TODO auto-generated Method Stub while(true) {semaphore.wait (empty, className); System.out.println (ClassName+ "Put a product into the buffer"); //randomly generated sleep time, which represents the time to put the product into operation LongMillis = (Long) (Math.random () * 1000); Try{thread.sleep (Millis); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } semaphore.signal (full, className); } } }); Thread Vistor=NewThread (NewRunnable () {String className= "Vistor"; @Override Public voidrun () {//TODO auto-generated Method Stub while(true) {semaphore.wait (full, className); System.out.println (ClassName+ "Take a product from the buffer"); LongMillis = (Long) (Math.random () * 1000); Try{thread.sleep (Millis); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } semaphore.signal (empty, className); } } }); /*** Indicates whether the buffer is full*/Semaphore empty; /*** Indicates whether the buffer is empty*/Semaphore full; PublicProductandvistor (Semaphore s1, Semaphore S2) { This. Empty =S1; This. Full =S2; } PublicProductandvistor () {Empty=NewSemaphore (1); full=NewSemaphore (0); } Public voidstart () {Producer.start (); Vistor.start (); } }
Synchronization of Java and operating system processes (ii) ———— Classic consumer producer issues