自己写的哲学家算法,大家看看这段代码是不是哲学家吃饭问题啊~自己感觉有点不对
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace EatingProblem
{
class Program
{
public static Mutex[] chop = new Mutex[5];//五个筷子,五个互斥对象
class ph
{
public void run()
{
// Monitor.Enter(this);
chop[int.Parse(Thread.CurrentThread.Name)].WaitOne();
chop[(int.Parse(Thread.CurrentThread.Name) + 1) % 5].WaitOne();
Console.WriteLine("哲学家{0} 正在吃东西", Thread.CurrentThread.Name);
Thread.Sleep(2000);
chop[int.Parse(Thread.CurrentThread.Name)].ReleaseMutex();
chop[(int.Parse(Thread.CurrentThread.Name) + 1) % 5].ReleaseMutex();
Console.WriteLine("哲学家{0} 正在思考问题", Thread.CurrentThread.Name);
Thread.Sleep(2000);
// Monitor.Exit(this);
}
}
static void Main(string[] args)
{
//for (int i = 0; i < 5; i++)
//{
// chop[i] = new Mutex(false);//开始时候,叉子都是空闲的
//}
for (int j = 0; j < 5; j++)
{
chop[j] = new Mutex();//设置的五个互斥对象,表示筷子。
}
ph p = new ph();
for (int i = 0; i < 100; i++)
{
Thread[] th = new Thread[5];
th[i%5] = new Thread(p.run);
th[i%5].Name = (i%5).ToString();
th[i%5].Start();
}
Console.ReadKey();
}
}
}