先擼一段代碼,再說
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace ThreadTest0902 { public class Program { bool bl = false; static void Main(string[] args) { Program p = new Program(); Thread thread = new Thread(p.Print); thread.Start(); p.Print(); Console.ReadKey(); } public void Print() { if (!bl) { Console.WriteLine("I'm False"); bl = true; } } } }
執行后你會發現,有時候打印一次,有時候會打印兩次
其實大家也能猜到是什么原因了,在第一個線程打印時,bl還是false,另一個線程進判斷語句了,於是也進來打印了
為了避免這樣無法預知的結果,於是我們就想着,在第一個線程(線程A)進行操作上,把門關上,鎖起來,另一個線程(線程B)只能在外面等着,等線程A處理好了,出去了,才可以讓線程B進來
於是微軟爸爸就給了我們把萬能鎖(lock)
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace ThreadTest0902 { public class Program { bool bl = false; static readonly object locker = new object(); static void Main(string[] args) { Program p = new Program(); Thread thread = new Thread(p.Print); thread.Start(); p.Print(); Console.ReadKey(); } public void Print() { lock (locker) { if (!bl) { Console.WriteLine("I'm False"); bl = true; } } } } }
單獨把這個拿出來說下
static object locker = new object();
一開始我只是寫成object locker = new object();
后來看了網上的代碼,看了下,基本上都是private static readonly於是我就客串下百度
private:如果該實例是public,那么無關的代碼也可能會鎖定該對象,那就會出現多個線程等待同一個對象釋放,導致死鎖
static:同上,如果是公共數據類型也會出現上述問題
readonly:一旦在lock中對象值變了,那么其他線程就可以進來執行了,因為互斥鎖的對象變了
菜鳥寶哥持續更新中...