线程同步——AutoResetEvent

作者:追风剑情 发布于:2017-9-21 11:00 分类:C#

控制线程同步

示例

  1. using System;
  2. using System.Threading;
  3.  
  4. namespace AutoResetEventTest
  5. {
  6. class Program
  7. {
  8. private static AutoResetEvent event_1 = new AutoResetEvent(true);
  9. private static AutoResetEvent event_2 = new AutoResetEvent(true);
  10.  
  11. static void Main(string[] args)
  12. {
  13. Thread myThread;
  14. for (int i = 0; i < 10; i++)
  15. {
  16. myThread = new Thread(new ThreadStart(MyThreadProc));
  17. myThread.Name = String.Format("Thread{0}", i + 1);
  18. myThread.Start();
  19. Thread.Sleep(1);
  20. }
  21.  
  22. Console.ReadKey();
  23. }
  24.  
  25. private static void MyThreadProc()
  26. {
  27. //线程按先后顺序依次执行something1和something2
  28. string name = Thread.CurrentThread.Name;
  29. //同时只允许1条线程执行something 1
  30. event_1.WaitOne();
  31. Console.WriteLine("{0} Thread do something 1...", name);
  32. Thread.Sleep(100);
  33. event_1.Set();
  34.  
  35. //同时只允许1条线程执行something 2
  36. event_2.WaitOne();
  37. Console.WriteLine("{0} Thread do something 2...", name);
  38. Thread.Sleep(100);
  39. event_2.Set();
  40. }
  41. }
  42. }

运行测试

1111.png

标签: C#

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号