1. AutoResetEvent类实现同步
如果要手动阻塞,可以使用ManualResetEvent
class Program
{
public static int target = 0; //主线程写
public static int count = 10; //主线程写target 次数
static AutoResetEvent autorest;
/// <summary>
/// 程序概述: 主线程写target变量,写完后子线程读target变量。实现线程同步工作
/// 实现:子线程通过waitone()方法等待主线程消息,主线程更新target变量后,通过autoset.Set()方法通知waitone等待的线程执行。
/// 由于resetEvent 声明的是AutoResetEvent,所以autoset不用手动设置 reset()方法,再一次阻塞线程,会自动阻塞。
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
//默认阻塞
autorest = new AutoResetEvent(false);
Thread readthread = new Thread(new ThreadStart(ReadTarget));
readthread.Start();
for(int i=0; i<count; i++)
{
Console.WriteLine($"主线程写:target={i}");
target = i;
//通知阻塞线程放弃阻塞
//autorest.Reset(); //继续阻塞线程;
autorest.Set();
Thread.Sleep(1000);
}
}
//读方法
static void ReadTarget()
{
Console.WriteLine("子线程开始");
//Console.WriteLine(autorest.WaitOne());
while (true)
{
autorest.WaitOne(); //阻塞
Console.WriteLine($"子线程读取:target={target}");
}
}
}