避免多线程冲突
多线程冲突 = 好几个人(线程)同时抢着改同一个数据 → 结果乱套、算错、报错!
using System;
using System.Threading;
class Program
{
static int count = 0;
// 🔥 定义一把锁(钥匙)
// 专门用来保护 count 这个数据
static object lockObj = new object();
static void Main()
{
Thread t1 = new Thread(AddCount);
Thread t2 = new Thread(AddCount);
t1.Start();
t2.Start();
t1.Join();
t2.Join();
// 加锁后,永远输出 2000
Console.WriteLine("最终结果:" + count);
}
static void AddCount()
{
for (int i = 0; i < 1000; i++)
{
// 🔥🔥🔥 加锁:只允许一个线程进入执行
// 谁拿到锁谁进,其他人在门口等
lock (lockObj)
{
// 安全区域:同一时间只有一个人修改 count
count++;
}
// 出了大括号,自动解锁,下一个线程进
}
}
}

浙公网安备 33010602011771号