您的位置:首页 > 其它

线程间同步与多线程

2014-08-14 16:32 211 查看
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Diagnostics;

namespace ConsoleApplication1
{

/// <summary>
/// 此类使用了ManualResetEvent,和AutoResetEvent
/// 功能一:ManualResetEvent用于,等待所有线程结束再执行
/// 功能二:AutoResetEvent用于线程间的同步
/// </summary>
class Program
{
#region === Filed ===
//定义两个资源
static int nSubOne = 20;
static int nSubTwo = 15;
//设置手动重置信号量
ManualResetEvent manA ;
ManualResetEvent manB ;

//设置自动重置信号量
AutoResetEvent ateA = new AutoResetEvent(false);
AutoResetEvent ateB = new AutoResetEvent(false);
#endregion === Filed ===

#region === Main Method ===

static void Main(string[] args)
{
Program pg = new Program();
pg.ThreadTest();
}

#endregion === Main Method ===

#region === Private Method ===
void ThreadTest()
{
//初始化信号量
manA = new ManualResetEvent(false);
manB = new ManualResetEvent(false);
//启动两个线程
Thread thdOne = new Thread(new ThreadStart(ThreadOne));
thdOne.Start();
Thread thdTwo = new Thread(new ThreadStart(ThreadTwo));
thdTwo.Start();

//等信号量manA,manB都释放了,才执行主线程
WaitHandle.WaitAll(new WaitHandle[2] { manA, manB });
int n = 0;
while (n < 10)
{
Debug.Print(n++.ToString());
Thread.Sleep(50);
}
}
void ThreadOne()
{
while (nSubOne > 0)
{
ateA.WaitOne();   //ateA保持等待
Debug.Print("T___1___:" + nSubOne--);
ateB.Set(); //给ateB一个开始信号
//Thread.Sleep(500);  //可以看出,线程一和线程2的Sleep时间并不一样,但是结果仍然是对的,
//这就是我们设置的同步信号量AutoResetEvent ateA,ateB的效果
}
manA.Set();  //给manA一个开始信号
}
void ThreadTwo()
{
ateA.Set();    //给ateA一个开始信号
//while (nSubTwo > 0)  //可以在这试一下另一个线程操作,看是否主线程的确是等所有其它线程都执行完成才执行的.
//即看一下WaitHandle.WaitAll是否是真的有效了.
while (nSubOne > 0)
{
ateB.WaitOne();  //ateB保持等待
//Console.WriteLine("T___2___:" + nSubTwo--);
Debug.Print("T___2___:" + nSubOne--);
ateA.Set();      //给ateA一个开始信号
//Thread.Sleep(50);
}
manB.Set(); //给manB一个开始信号
}
#endregion === Custom Method ===

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: