我发一个C#做的就餐问题的模拟程序, 用 5 个线程模拟 5 个哲学家。
-
-
- using System;
- using System.Collections.Generic;
- using System.Text;
- using System.Threading;
-
- namespace Philosopher
- {
- class Fork
- {
- const int NOBODY = -1;
- int Owner = NOBODY;
- public Fork() { }
-
- public bool IsTakenBy(Philosopher p) { return p.ID == Owner; }
-
- public void TakenBy(Philosopher p)
- {
- if (Owner == NOBODY)
- Owner = p.ID;
- }
-
- public void PutBy(Philosopher p)
- {
- if (p.ID == Owner)
- Owner = NOBODY;
- }
- }
-
- class Philosopher
- {
- bool ThreadRunning;
- Thread DinningThread;
- public int ID;
- public Fork Left;
- public Fork Right;
-
- public Philosopher(int id, Fork left, Fork right)
- {
- ID = id;
- Left = left;
- Right = right;
- DinningThread = new Thread(StartDinning);
- DinningThread.Start();
- }
-
- public void Think() { Thread.Sleep(1000); }
-
- public void Dine()
- {
- lock (this) {
- Left.TakenBy(this);
- Right.TakenBy(this);
- }
- if (Left.IsTakenBy(this) && Right.IsTakenBy(this)) {
- Console.WriteLine("Philosopher " + ID.ToString() + " is dining.");
- Thread.Sleep(1000);
- }
- lock (this) {
- Left.PutBy(this);
- Right.PutBy(this);
- }
- }
-
- public void Stop() { ThreadRunning = false; }
- void StartDinning()
- {
- ThreadRunning = true;
- while (ThreadRunning) {
- Think();
- Dine();
- }
- }
- }
-
- class Program
- {
- static void Main(string[] args)
- {
- Fork[] forks = new Fork[] { new Fork(), new Fork(), new Fork(), new Fork(), new Fork() };
- Philosopher[] philosophers = new Philosopher[5];
- for (int i = 0; i < 5; i++) {
- philosophers[i] = new Philosopher(i, forks[i], forks[(i + 4) % 5]);
- }
- Console.Read();
- for (int i = 0; i < 5; i++)
- philosophers[i].Stop();
- }
- }
- }
|