lock(獨佔)、Semaphore(計數信號,允許 N 線程進入)AutoResetEvent(自動重置)、ManualResetEvent(手動重置)Interlocked 原子操作同步機制無法保證線程按預期順序執行(OS 排程不可預測),濫用大範圍鎖會將多線程退化為單線程,效能反而下降。
static int result = 0;
static object locker = new object();
for (int i = 0; i < 10; i++)
{
new Thread(() =>
{
if (Monitor.TryEnter(locker, 2000)) // 2 秒超時
{
Thread.Sleep(1000);
Console.WriteLine(DateTime.Now.ToString("mm:ss"));
Monitor.Exit(locker);
}
}).Start();
}

前 3 線程依序獲取鎖(各耗 1 秒),第 4 線程等待 2 秒超時返回 false 結束,後續同理。Monitor.TryEnter 避免無限期阻塞,適合需超時控制場景。