C# 使用 AutoResetEvent 或 ManualResetEvent 同步两个线程

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading;
 6 
 7 namespace ThreadTest
 8 {
 9     class Program
10     {
11         // 信号 
12         static AutoResetEvent ar = new AutoResetEvent(false);
13 
14         // 一个公用的变量
15         static int i = 0;
16 
17         // Thread Method 1
18         static void WriteMethod(object state) {
19             while (i < 10) {
20                 Thread.Sleep(1000);
21                 i++;
22                 //Console.WriteLine("{1} Write i : {0}", i, Thread.CurrentThread.Name);
23                 Console.WriteLine("{1} Write i : {0}", i, (string)state);
24                 ar.Set();
25             }
26         }
27 
28         // Thread Method 2
29         static void ReadMethod(object state) {
30             while (true) {
31                 ar.WaitOne();
32                 //Console.WriteLine("{1} Read i : {0}", i, Thread.CurrentThread.Name);
33                 Console.WriteLine("{1} Write i : {0}", i, (string)state);
34             }
35         }
36 
37         static void Main(string[] args) {
38             // 开启 写入线程
39             // 线程池方法
40             ThreadPool.QueueUserWorkItem(WriteMethod,"Write Thread ");
41 
42             // 普通开线程方法
43             //Thread write = new Thread(new ThreadStart(WriteMethod));
44             //write.Name = "Write Thread ";
45 
46             // 如果是后台线程,需要 一个 Console.ReadKey 等待
47             //write.IsBackground = true;
48             //write.Start();
49 
50             // 开启 读取线程
51             // 线程池方法
52             ThreadPool.QueueUserWorkItem(ReadMethod,"Read Thread ");
53 
54             // 普通开线程方法
55             //Thread read = new Thread(new ThreadStart(ReadMethod));
56             //read.Name = "Read Thread ";
57 
58             // 如果是后台线程,需要 一个 Console.ReadKey 等待
59             //read.IsBackground = true;
60             //read.Start();
61 
62             // 如果使用线程池方法的时候.线程都是 后台线程. Console 会立即结束.所以需要这个方法来阻塞主线程
63             Console.ReadKey();
64         }
65     }
66 }

 

posted @ 2013-06-17 21:49  easyfrog  阅读(388)  评论(0编辑  收藏  举报