Bootstrap

C# 多线程学习

int count = 0;
const int total = 100_000;
object lockobj = new object();

var thread1 = new Thread(ThreadMethod);
var thread2 = new Thread(ThreadMethod);

thread1.Start();
thread2.Start();

thread1.Join();
thread2.Join();

Console.WriteLine($"count:{count}");
//不加锁时候,count 并不等于200000

void ThreadMethod(object? obj)
{
    for (int i = 0; i < total; i++)
    {
       // lock (lockobj)
        //{
            count++;
        //}
      
    }
}

;