📄 class1.cs
字号:
using System;
using System.Threading;
namespace Exam7_6
{
/// <summary>
/// Class1 的摘要说明。
/// </summary>
class ChopStick
{ //筷子类
AutoResetEvent eventX;
int n;
public ChopStick(int n)
{
eventX = new AutoResetEvent(true);
this.n=n;
}
public void takeup(String name)
{ //拿起筷子
lock(this)
{
System.Console.WriteLine(name+"在等待拿起第"+n+"个筷子");
eventX.WaitOne();
Console.WriteLine(name+"拿起第"+n+"个筷子");
}
}
public void putdown(String name)
{ //放下筷子
eventX.Set();
Console.WriteLine(name+"放下第"+n+"个筷子");
}
}
class Philosopher
{
ChopStick left,right;
String name;
public Philosopher(String name,ChopStick left,ChopStick right)
{
this.name=name;
this.left=left;
this.right=right;
}
public void think()
{ //思考问题
left.putdown(name); //放下左筷子
right.putdown(name); //放下右筷子
System.Console.WriteLine(name+"在思考....");
}
public void eat()
{
left.takeup(name);
right.takeup(name);
System.Console.WriteLine(name+"在吃饭....");
}
public void run()
{
while(true)
{
eat();
Thread.Sleep(1000);
think();
Thread.Sleep(1000);
}
}
}
class Dining
{
static ChopStick []cp=new ChopStick[5];
static Philosopher []ph=new Philosopher[5];
public static void Main()
{
for(int n=0;n<5;n++)
{
cp[n]=new ChopStick(n);
}
for(int n=0;n<5;n++)
{
ph[n]=new Philosopher("哲学家"+n,cp[n],cp[(n+1)%5]);
}
for(int n=0;n<5;n++)
{
Thread th=new Thread(new ThreadStart(ph[n].run));
th.Start();
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -