using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Test { class Program { static void Main(string[] args) { var ins= new TestClass(); for (int i = 0; i < 100; i++) { Task.Factory.StartNew(() => { ins.test(); }); } Console.ReadLine(); } } public class TestClass { public static int num = 0; static object lockObjStatic = new object(); object lockObj = new object(); public void test() { object lockObjtemp = new object(); //lockObjtemp 無論是否同一個對象,鎖都不起作用 //lockObj 同一個對象下鎖起作用,不通的對象下鎖不起作用 //lockObjStatic 不管同一個對象還是非同一個對象鎖都起作用 lock (lockObjStatic) //正常用鎖的時候,一定要鎖定私有靜態字段 { add(); } } public void add() { num++; Console.WriteLine(TestClass.num); } } }
