using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading; namespace ThreadTest
{
class Program
{
// 信号
static AutoResetEvent ar = new AutoResetEvent(false); // 一个公用的变量
static int i = ; // Thread Method 1
static void WriteMethod(object state) {
while (i < ) {
Thread.Sleep();
i++;
//Console.WriteLine("{1} Write i : {0}", i, Thread.CurrentThread.Name);
Console.WriteLine("{1} Write i : {0}", i, (string)state);
ar.Set();
}
} // Thread Method 2
static void ReadMethod(object state) {
while (true) {
ar.WaitOne();
//Console.WriteLine("{1} Read i : {0}", i, Thread.CurrentThread.Name);
Console.WriteLine("{1} Write i : {0}", i, (string)state);
}
} static void Main(string[] args) {
// 开启 写入线程
// 线程池方法
ThreadPool.QueueUserWorkItem(WriteMethod,"Write Thread "); // 普通开线程方法
//Thread write = new Thread(new ThreadStart(WriteMethod));
//write.Name = "Write Thread "; // 如果是后台线程,需要 一个 Console.ReadKey 等待
//write.IsBackground = true;
//write.Start(); // 开启 读取线程
// 线程池方法
ThreadPool.QueueUserWorkItem(ReadMethod,"Read Thread "); // 普通开线程方法
//Thread read = new Thread(new ThreadStart(ReadMethod));
//read.Name = "Read Thread "; // 如果是后台线程,需要 一个 Console.ReadKey 等待
//read.IsBackground = true;
//read.Start(); // 如果使用线程池方法的时候.线程都是 后台线程. Console 会立即结束.所以需要这个方法来阻塞主线程
Console.ReadKey();
}
}
}
05-07 15:18