Monitor 类提供了同步对对象的访问机制,它通过单个线程授予对象锁来控制对象的访问,对象锁提供限制访问代码块,(通常称为临界区)的能力.当一个线程拥有对象锁时,其他任何线程都不能获取该锁,功能和 lock 关键字类似
常用方法:
示例代码:
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Account ac = new Account();
for (int i = 0; i < 3; i++)
{
Thread th = new Thread(ac.TestRun);
th.Start();
}
Console.Read();
}
}
class Account
{
private Object obj = new object();
private int i = 0;
public void TestRun() {
Monitor.Enter(obj);
//后面代码只能被一个线程调用,这样看来obj似乎就是个密匙,没有他就别想运行
Console.WriteLine("i的初始值为:"+i.ToString());
Thread.Sleep(1000);//模拟耗时工作
i++;
Console.WriteLine("i在自增长后的值:"+i.ToString());
//解除锁
Monitor.Exit(obj);
}
}
}
效果: