关于线程的例子
下面是两个线程,每个线程循环10000次,结果应该是20000,运行一下程序,是不是想要的结果
public static void Main(string[] args)
{var thread1 = new System.Threading.Thread(ThreadMethod);var thread2 = new System.Threading.Thread(ThreadMethod);thread1.Start();thread2.Start();thread1.Join();thread2.Join();Debug.WriteLine($"Count: {count}");Console.ReadLine();
}static int count = 0;
static int total = 10000;
static void ThreadMethod()
{for (int i = 0; i < total; i++){count++;}
}
运行后结果总是1w多点,而不是2W,
下面给出2中解决方案
第一种是用lock
public static void Main(string[] args){var thread1 = new System.Threading.Thread(ThreadMethod);var thread2 = new System.Threading.Thread(ThreadMethod);thread1.Start();thread2.Start();thread1.Join();thread2.Join();Debug.WriteLine($"Count: {count}");Console.ReadLine();}static int count = 0;static int total = 10000;private static object m_obj = new object();static void ThreadMethod(){for (int i = 0; i < total; i++){lock (m_obj){count++;}}}
第二种,直接用.ne提供的框架中的Interlocked
public static void Main(string[] args){var thread1 = new System.Threading.Thread(ThreadMethod);var thread2 = new System.Threading.Thread(ThreadMethod);thread1.Start();thread2.Start();thread1.Join();thread2.Join();Debug.WriteLine($"Count: {count}");Console.ReadLine();}static int count = 0;static int total = 10000;static void ThreadMethod(){for (int i = 0; i < total; i++){Interlocked.Increment(ref count);}}