class Program
{static void Main(string[] args){A a1 = new A();A a2 = new A();Thread T1 = new Thread(new ParameterizedThreadStart(a1.Test));Thread T2 = new Thread(new ParameterizedThreadStart(a2.Test));T1.Start(2);T2.Start(5);Console.Read();}
}
public class A
{public static Int32 Count = 2;public void Test(object i){lock (this){Console.WriteLine("Count={0}", Count);Count += (Int32)i;Thread.Sleep(1 * 1000);Console.WriteLine("i={0},?Count+i={1}", i, Count);Console.WriteLine("--------------------------");}}
}
public class A
{private static object obj = new object();public static Int32 Count = 2;public void Test(object i){lock (obj){Console.WriteLine("Count={0}", Count);Count += (Int32)i;Thread.Sleep(1 * 1000);Console.WriteLine("i={0},?Count+i={1}", i, Count);Console.WriteLine("--------------------------");}}
}
這里的線程已經正常工作了,Count也正常的累加。
lock (obj)怎么錯誤了? 上面正常運行的程序稍微改動下!
class Program
{static void Main(string[] args){A a1 = new A();A a2 = new A();Thread T1 = new Thread(new ParameterizedThreadStart(a1.Test));Thread T2 = new Thread(new ParameterizedThreadStart(a2.Test));T1.Start(2);T2.Start(5);Console.Read();}
}
public class A
{private object obj = new object();public static Int32 Count = 2;public void Test(object i){lock (obj){Console.WriteLine("Count={0}", Count);Count += (Int32)i;Thread.Sleep(1 * 1000);Console.WriteLine("i={0},?Count+i={1}", i, Count);Console.WriteLine("--------------------------");}}
}
class Program
{static void Main(string[] args){A a1 = new A();Thread T1 = new Thread(new ParameterizedThreadStart(a1.Test));Thread T2 = new Thread(new ParameterizedThreadStart(a1.Test));T1.Start(2);T2.Start(5);Console.Read();}
}