Public Class Cell
{
Bool Flags = False ;
Int Result = 0 ;
Public Void Write ( Int N)
{
Lock ( This )
{
If (Flags)
{
Try
{
Monitor. Wait ( This );
}
Catch (Threadstartexception E)
{
Console. writeline (E );
}
}
Result = N;
Console. writeline ( " Write: {0} " , Result );
Flags = True ;
Monitor. Pulse ( This );
}
}
Public Int Read ()
{
Lock ( This )
{
If (! Flags)
{
Try
{
Monitor. Wait ( This );
}
Catch (Threadstartexception E)
{
Console. writeline (E );
}
}
Console. writeline ( " Read: {0} " , Result );
Flags = False ;
Monitor. Pulse ( This );
Return Result;
}
}
}
Public Class Cellprod
{
Cell cell; // Cell object to be operated
Int Quantity =1 ; // Producer production count, initialized to 1
Public Cellprod (cell box, Int Request)
{
// Constructor
Cell = box;
Quantity = request;
}
Public Void Threadrun ()
{
For ( Int Logoff = 1 ; Loty <= quantity; Looper ++)
Cell. Write (logoff ); // The producer writes information to the operation object.
}
}
Public Class Cellcons
{
Cell cell;
Int Quantity = 1 ;
Public Cellcons (cell box, Int Request)
{ // Constructor
Cell = box;
Quantity = request;
}
Public Void Threadrun ()
{
Int Valreturned; For ( Int Logoff = 1 ; Loty <= quantity; Looper ++)
Valreturned = cell. Read (); // The consumer reads information from the operation object.
}
}
Class Program
{
Public Static Void Add ()
{
Int Result = 0 ;// A flag. If it is 0, it indicatesProgramNo error. If it is 1, an error occurs.
Cell cell = New Cell (); // The following two classes cellprod and cellcons are initialized using cell. The number of times of production and consumption is 20.
Cellprod write = New Cellprod (cell, 20 );
Cellcons READ = New Cellcons (cell, 20 );
Thread writeth = New Thread ( New Threadstart (write. threadrun ));
Thread readth = New Thread ( New Threadstart (read. threadrun )); // Both the producer thread and consumer thread have been created, but execution has not started.
Try
{
Readth. Start ();
Writeth. Start ();
Readth. Join ();
Writeth. Join ();
Console. Readline ();
}
Catch (Threadstateexception E)
{
// When the thread cannot perform the requested operation because of its status
Console. writeline (E); Result = 1 ;
}
Catch (Threadinterruptedexception E)
{
// Abort when the thread is waiting
Console. writeline (E); Result = 1 ;
} // Although the main () function does not return a value, the following statement can return the execution result to the parent process.
Environment. exitcode = result;
}
Static Void Main ( String [] ARGs)
{
Program. Add ();
}
in the preceding routine, synchronization is completed by waiting for monitor. Pulse. First, the producer produces a value, while the consumer is in the waiting state at the same time until it receives the "pulse" notification from the producer that production has been completed, and then the consumer enters the consumption state, the producer will call monitor after waiting for the consumer to complete the operation. the "pulse" emitted by pulese ".