111,094
社区成员




using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
namespace 哲学家进餐问题
{
public partial class Form1 : Form
{
private Thread[] phiThreads;
private Chopsticks[] chopsticks;
private Random random;
private object SyncObject;
delegate void SetTextCallback(ListBox control, string text);
public Form1()
{
InitializeComponent();
init();
}
private void 停止_Click(object sender, EventArgs e)
{
abort();
}
private void 开始_Click(object sender, EventArgs e)
{
for (int i = 0; i < 5; i++)//初始化5个哲学家,执行phiAction方法
{
phiThreads[i] = new Thread(new ParameterizedThreadStart(phiAction));
phiThreads[i].Name = i.ToString();
phiThreads[i].Start(i);
}
}
private void 退出_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void UpdateListBox(ListBox control, string text)
{
SyncObject = new object();
if (control.InvokeRequired) //用于在Listbox中添加text
{
SetTextCallback d = new SetTextCallback(UpdateListBox);
this.Invoke(d, new object[] { control, text });
}
else
{
lock (SyncObject)
{
control.Items.Add(text);
}
}
}
private void print(int who,string str)
{
string printStr = who.ToString() + str;
lock(this)
{
UpdateListBox(listBox1, printStr); //在Listbox中添加条目
}
}
private void init()
{
phiThreads = new Thread[5];
chopsticks = new Chopsticks[5];
random = new Random();
}
private void abort()
{
for (int i = 0;i<5;i++)
{
phiThreads[i].Abort();//结束线程
}
}
private void phiAction(object index)
{
while(true)
{
Thinking(index);
Waiting(index);
Eating(index);
int sleepTime = random.Next(100, 500);
Thread.Sleep(sleepTime + 500);
}
}
private void Thinking(object index)
{
print((int)index, " is thinking...");
int sleepTime = random.Next(100, 500);
Thread.Sleep(sleepTime + 500);
}
private void Eating(object index)
{
print((int)index, " is eating...");
int sleepTime = random.Next(100, 500);
Thread.Sleep(sleepTime + 500);
chopsticks[(int)index].chopsSem.Release(); //释放右边的筷子
chopsticks[((int)index+1) % 5].chopsSem.Release(); //释放左边的筷子
}
private void Waiting(object index)
{
print((int)index, " is waiting...");
int sleepTime = random.Next(100, 500);
Thread.Sleep(sleepTime + 500);
if ((int)index % 2 == 0)//偶数号哲学家
{
chopsticks[(int)index].chopsSem.WaitOne(); //获取右边的筷子
chopsticks[(int)index + 1 % 5].chopsSem.WaitOne(); //获取左边的筷子
}
else//奇数号哲学家
{
chopsticks[(int)index + 1 % 5].chopsSem.WaitOne(); //获取左边的筷子
chopsticks[(int)index].chopsSem.WaitOne(); //获取右边的筷子
}
}
}
}
public class Chopsticks
{
public Semaphore chopsSem;
Chopsticks()
{
chopsSem = new Semaphore(1, 1);
}
}