这是一个简单的 C# 示例程序的稍微修改版本:
using System;
using System.Threading;
namespace SemaphorTest
{
class Program
{
static Semaphore gate = new Semaphore(3, 3);
static void Main(string[] args)
{
for (int i = 0; i < 5; i++)
{
Thread t = new Thread(Enter);
t.Start(i);
}
}
public static void Enter(Object id)
{
Console.WriteLine("Thread " + id + " wants to enter.");
gate.WaitOne();
Console.WriteLine("Thread " + id + " is in.");
Thread.Sleep(500 * (Int32)id);
Console.WriteLine("Thread " + id + " leaving.");
gate.Release();
}
}
}
这将打印以下输出(似乎是随机顺序):
Thread 0 wants to enter.
Thread 1 wants to enter.
Thread 1 is in.
Thread 0 is in.
Thread 2 wants to enter.
Thread 3 wants to enter.
Thread 0 leaving.
Thread 3 is in.
Thread 4 wants to enter.
Thread 2 is in.
Thread 1 leaving.
Thread 4 is in.
Thread 2 leaving.
Thread 3 leaving.
Thread 4 leaving.
但是,如下添加 Thread.Join() 会极大地改变输出。即:
for (int i = 0; i < 5; i++)
{
Thread t = new Thread(Enter);
t.Start(i);
t.Join();
}
将输出更改为:
Thread 0 wants to enter.
Thread 0 is in.
Thread 0 leaving.
Thread 1 wants to enter.
Thread 1 is in.
Thread 1 leaving.
Thread 2 wants to enter.
Thread 2 is in.
Thread 2 leaving.
Thread 3 wants to enter.
Thread 3 is in.
Thread 3 leaving.
Thread 4 wants to enter.
Thread 4 is in.
Thread 4 leaving.
为什么会这样?我知道这些线程默认是前台线程,并且主线程不需要等待它们完成(即使在 Main 完成后它们也会运行,因此它们在这里不需要 thread.Join())。但我不明白是什么让它们按照更改后创建的顺序运行。有任何想法吗 ?
Thanks
Dileep Balakrishnan