- 1、使用lock语句
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp3
{
class Program
{
static void Main(string[] args)
{
Program p = new Program();
//实例化对象
p.lockthread();
//调用lock锁定线程的方法
}
void lockthread()
//定义lockthread方法
{
lock(this)
{
Console.WriteLine("Lock实例");
}
}
}
}
结果
- 2、使用Monitor类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;//注意加上这个命名空间
namespace ConsoleApp4
{
class Program
{
static void Main(string[] args)
{
Program p = new Program();
p.lockthread();
}
void lockthread()
{
Monitor.Enter(this);
//锁定线程
Console.WriteLine("Monitor线程同步实例");
Monitor.Exit(this);
//释放线程
}
}
}
结果
- 3、使用Mutex类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace ConsoleApp5
{
class Program
{
static void Main(string[] args)
{
Program p = new Program();
//实例化对象
p.lockthread();
//调用lockthread方法
}
void lockthread()
{
Mutex m = new Mutex(false);
//实例化Mutex对象
m.WaitOne();
//阻止当前线程
Console.WriteLine("Mutex类线程同步实例");
m.ReleaseMutex();
//释放Mutex对象
}
}
}
结果