另一篇在 CSDN 也是有問題的程式,程式的目的是限制一定數量的 threads 同時執行某項工作。我的想法是用 System.Threading.Monitor 就可以很優雅地解決這問題:
class Program
{
static void Main(string[] args)
{
Program p = new Program();
Thread[] threads = new Thread[10];
for (int i = 0; i < threads.Length; i++)
{
threads[i] = new Thread(p.Run);
threads[i].Name = "Thread(" + i.ToString() + ")";
threads[i].Start();
Thread.Sleep(1000);
}
foreach (Thread t in threads) {
t.Join();
}
Console.ReadLine();
}
private int allowed = 3;
public void Run()
{
Thread t = Thread.CurrentThread;
lock (this)
{
while (allowed <= 0)
{
Console.WriteLine(t.Name + " is waiting.");
Monitor.Wait(this);
}
--allowed;
Console.WriteLine(t.Name + " started.");
}
Thread.Sleep(2000);
lock (this)
{
Console.WriteLine(t.Name + " stopped.");
++allowed;
Monitor.Pulse(this);
}
}
}
說穿了其實這程式只是用 Monitor 來實作 Semaphore 的一個特別例子。