使用 static 修飾詞讓欄位屬於類別而非實例,所有執行緒存取同一份記憶體位置:
class MyThread {
static Queue q1 = new Queue();
static int b = 0;
public void DoFun() {
lock (this) { // 同步區塊
++b;
q1.Enqueue(b);
}
Console.WriteLine("B:{0}--------------", b);
PrintValues(q1);
}
public static void PrintValues(IEnumerable myCollection) {
IEnumerator myEnumerator = myCollection.GetEnumerator();
while (myEnumerator.MoveNext()) Console.Write("\t{0}", myEnumerator.Current);
Console.WriteLine();
}
}
class ClassMain {
[STAThread]
static void Main(string[] args) {
MyThread myc = new MyThread();
Thread[] myt = new Thread[10];
for (int i = 0; i < 10; ++i) {
myt[i] = new Thread(new ThreadStart(myc.DoFun));
myt[i].Start();
Thread.Sleep(1000); // 主執行緒休眠 1 秒
}
Console.Read(); // 等待按鍵防止視窗關閉
}
}
| 概念 | 說明 |
|---|---|
static 欄位 | 跨實例共享,AppDomain 內單一拷貝 |
lock (this) | 互斥鎖,確保遞增與入隊操作原子性 |
ThreadStart 委派 | 指向無參數無回傳值的方法 |
Thread.Sleep | 讓出 CPU 時間片,觀察交錯執行效果 |
lock (privateObj) 而非 lock (this),避免外部程式碼取得同一個鎖物件造成死結ConcurrentQueue<T>、Interlocked.Increment 等無鎖集合與原子操作提升效能