线程间同步与多线程
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 === } }
相关文章推荐
- !!! 多线程编程+MFC中的多线程开发+线程间通讯+线程的同步
- C++拾遗--多线程:主线程与子线程的同步
- 进程 线程 多线程 并发 同步异步
- 多线程编程之四——线程的同步
- java多线程:线程的同步与锁
- 多线程编程——线程的同步(六)
- 多线程编程13-----Exchanger同步工具类实现两线程数据交换
- Java多线程-线程的同步(同步方法)
- 【多线程】【同步】【等待唤醒机制】【JDK1.5多线程】【线程优先级&常见方法】
- 多线程编程之四——线程的同步
- 多线程编程之四——线程的同步
- 多线程编程之四——线程的同步
- 多线程第三篇 经典线程同步之关键段CS
- Java多线程-线程的同步与锁
- Java 多线程详解(三)------线程的同步
- 多线程编程之四——线程的同步
- 多线程(三)——线程的同步,synchronized关键字的使用
- java 多线程:开两个线程,一个线程跑同步代码块,一个线程跑同步函数
- Linux下面线程的操作、多线程的同步和互斥
- java多线程学习-同步之线程通信