看板 C_Sharp 關於我們 聯絡資訊
※ 引述《kenshinn (子凌(b))》之銘言: : ※ 引述《missbus (smile)》之銘言: : 前文述刪 : 看了閣下的程式後 : 關鍵在於 : new Thread(new ThreadStart(new hello(1).add)).Start(); : new Thread(new ThreadStart(new hello(2).add)).Start(); : 使得兩條 Thread 以一前一後的方式開始執行 : 接著在 Add 方法中 : public void add() : { : for (int k = 0; k < 10; k++) : { : lock (this) ^^^^ 不太了解為什麼要用this, 這樣好像每個this的東西不一樣. 可以試著在你的 class hello 裡面宣告一個 static object locker = new object(); 然後使用lock(locker) 應該可以達到你要的目的. : { : test.hello[1, 1] += 1; : Console.WriteLine("hello object " + i + " -- " + : Thread.CurrentContext.ToString() + : " -- " + test.hello[1, 1]); : } : } : } : 雖然有 lock 但是兩條 Thread 並行的結果,使得在離開 lock 後另一條 Thread 的 : 函式有機可趁,故結果是無法預測的 -- If people do not believe that mathematics is simple, it is because they do not realize how complicated life is. -- John Louis von Neumann -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 220.133.58.208
powertodream:而且lock 要放在for外面. 08/04 23:58