线程通知
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace ThreadTest
{
class Program
{
///用static来构造AutoresetEvetn就没有必要再构造函数构造,而且在main函数之前
/// 就已经构造好了
private static AutoResetEvent myResetEvent = new AutoResetEvent(false);
private static int number;
static void MyreadThreadProc()
{
while (true)
{
///等待接受信号然后读出
myResetEvent.WaitOne();
Console.WriteLine("{0}读到的值是:{1}", Thread.CurrentThread.Name, number);
}
}
static void Main(string[] args)
{
Thread myReadThread = new Thread(new ThreadStart(MyreadThreadProc));
myReadThread.Name = "读进程";
myReadThread.Start();
for(int i = 0; i <100;i++)
{
Console.WriteLine("写进程写的是{0}", i);
number = i;
myResetEvent.Set();
Thread.Sleep(1);
}
}
}
}
</pre><pre code_snippet_id="1863795" snippet_file_name="blog_20160902_3_8848226" name="code" class="csharp">
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace ThreadTest
{
/// <summary>
/// 一个很简单的例子来演示waitany和waitall
/// 注意都是静态方法 所以用Autoresetevent...
/// </summary>
class Person
{
private AutoResetEvent[] autoResetEvent;
public Person()
{
autoResetEvent = new AutoResetEvent[]
{
new AutoResetEvent(false),
new AutoResetEvent(false),
new AutoResetEvent(false),
};
}
/// 定义线程处理事件
public void GetCar()
{
Console.WriteLine("我捡到宝马了");
autoResetEvent[0].Set();
}
public void GetMoney()
{
Console.WriteLine("我赚到钱啦");
autoResetEvent[1].Set();
}
public void GetWife()
{
Console.WriteLine("我骗到老婆啦");
autoResetEvent[2].Set();
}
static void Main(string[] args)
{
///设置三个线程
Person p = new Person();
Thread threadA = new Thread(new ThreadStart(p.GetCar));
threadA.Start();
Thread threadB = new Thread(new ThreadStart(p.GetMoney));
threadB.Start();
Thread threadC = new Thread(new ThreadStart(p.GetWife));
threadC.Start();
AutoResetEvent.WaitAll(p.autoResetEvent);
Console.WriteLine("生活如此美好");
}
}
}