Code
Using system;
Using system. text;
Using system. Threading;
Namespace readkey
{
Class program3
{
Static void main (string [] ARGs)
{
Student = new student ();
New thread (New threadstart (New thread1 (student). Run). Start (); // Add information
New thread (New threadstart (New thread2 (student). Run). Start (); // read information
}
}
/// <Summary>
/// Add information to the Student Class
/// </Summary>
Public class thread1
{
Private student;
Public thread1 (Student)
{
This. Student = student;
}
Public void run ()
{
Int I = 0;
While (true)
{
If (I = 0)
Student. Add ("jxncwzb", 23 );
Else
Student. Add ("jxncwzb ++", 22 );
I = (I + 1) % 2;
}
}
}
/// <Summary>
/// Read the information added by thread1.
/// </Summary>
Public class thread2
{
Private student;
Public thread2 (Student)
{
This. Student = student;
}
Public void run ()
{
While (true)
{
Student. getinfo ();
}
}
}
Public class student
{
Private string name;
Private int age;
Private bool isrun = false;
Public void add (string name, int age)
{
Monitor. Enter (this );
If (isrun)
Monitor. Wait (this );
This. Name = Name;
// Thread. Sleep (10 );
This. Age = age;
This. isrun = true;
Monitor. Pulse (this );
Monitor. Exit (this );
}
Public void getinfo ()
{
Monitor. Enter (this );
If (! Isrun)
Monitor. Wait (this );
Console. Write ("name:" + name );
Console. writeline ("& age:" + age. tostring ());
This. isrun = false;
Monitor. Pulse (this );
Monitor. Exit (this );
}
}
}