// multiple producers and multiple consumers, where n can produce a product using System; using System.Threading; public class HoldIntegerSynchronized {private int [] buffer; // buffer private int occupiedBufferCount = 0; private int readPosition = 0, WritePosition = 0; // The next read position and the location written PUBLIC HOLDINTEGERSYNCHRONIZED (INT CAPACITY) {Buffer = new int [Capacity];} public int buffer.length;}} public INT buffer {get {int buffercopy; // Plock Lock (this) {while (occupiedbuffercount == 0) {// Multiple consumers, so this is done with while console.writeline (thread.currentthread.name "Tries To read. "); DisplayState (" Buffer Empty. " Thread.currentthread.name " Waits. "); Monitor.wait (this); // For the producers waiting for the critical area, let him come" Production "// Continued until the producer production ended, calling Monitor.PauseAll () // can continue to execute, at this time, consumers automatically remember the lock} --occupiedbuffercount; buffercopy = buffer [readPosition]; readposition = (ReadPosition 1)% Buffer.Length; DisplayState (thread.currentthread.name "r buffercopy); // Notification, let the waiter thread enter S Tarted status, if the producer is in the critical area, he is still outside the critical area Monitor.pulseall (this); // Release lock} // Lock Return Buffercopy;} set {// Unlock lock (this) {while (occupiedBufferCount == buffer.Length) {Console.WriteLine (Thread.CurrentThread.Name "tries to write."); DisplayState ( Thread.CurrentThread.Name "waits" Buffer Full. ". "); Monitor.wait (this); // Waiting for consumers outside the critical area, let him" consumption "// until the consumer calls Monitor.Pause () // can continue, at this time Producers automatically re-acquire this lock} buffer [WritePosition] = Value;
OccupiedBuffercount; WritePosition = (WritePosition 1)% Buffer.Length; DISPLAYSTATE (thread.currentthread.name "WRITES" value); // Notice, let the consumer of the WAIT state enters the Started state, if the consumer is in the critical area In addition, he is still outside of the critical area. Monitor.pulseall (THIS); // Release lock}}}}}}}} {console.write ("{0, -35}", Operation); for (int i = 0; i