为什么要用锁,防止多个线程对一个共享资源进行访问出现的异常
using System;
using System.Threading;
namespace ThreadDemo3
{
class Program
{
static int i = 1;
static void Main(string[] args)
{
Program program = new Program();
//for (int i = 0; i < 5; i++)
//{
// Thread thread = new Thread(program.Run);
// thread.Start();
//}
Thread thread = new Thread(program.Run);
thread.Start();
Thread thread1 = new Thread(program.Run);
thread1.Start();
Console.ReadKey();
}
void Run()
{
object locker = new object();
//最好是个object对象,私用
//不建议使用lock(this);因为this锁定的是当前对象,如果又多个对象方法就会出现没有同步的问题
lock (locker)
{
if (i > 0)
{
Thread.Sleep(1000);
i--;
Console.WriteLine(i);
}
else
{
Console.WriteLine("-99");
}
}
}
}
}