代码
using System;
using System.Text;
using System.Threading;


namespace ReadKey
{
class Program3
{
static void Main(string[] args)
{
Student student
= new Student();
new Thread(new ThreadStart(new Thread1(student).run)).Start();//添加信息
new Thread(new ThreadStart(new Thread2(student).run)).Start();//读取信息
}
}

/// <summary>
/// 向Student类加添加信息
/// </summary>
public class Thread1
{
private Student student;
public Thread1(Student 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>
/// 读取Thread1干才添加的信息
/// </summary>
public class Thread2
{
private Student student;
public Thread2(Student 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);
Console.WriteLine(
"&年龄:" + age.ToString());
this.isRun = false;
Monitor.Pulse(
this);
Monitor.Exit(
this);
}

}
}

 

相关文章:

  • 2022-12-23
  • 2021-07-15
  • 2022-01-09
  • 2021-10-27
  • 2021-11-28
  • 2021-08-07
  • 2022-03-08
猜你喜欢
  • 2022-12-23
  • 2021-07-27
  • 2022-12-23
  • 2021-07-03
  • 2022-02-17
  • 2022-02-23
  • 2021-06-14
相关资源
相似解决方案