C # monitor multi-thread Communication

Source: Internet
Author: User
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 );
}

}
}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.