111,023
社区成员
发帖
与我相关
我的任务
分享
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
//堆栈是后进先出的
static System.Collections.Stack stack = new System.Collections.Stack();
//信号量控制线程
static System.Threading.ManualResetEvent obj = new System.Threading.ManualResetEvent(false);
//写入的对象
public class Data
{
public Guid ID = Guid.NewGuid();
public string ThreadName = System.Threading.Thread.CurrentThread.Name;
public override string ToString()
{
return string.Format("{0}生成的{1}", ThreadName, ID);
}
}
static void Main(string[] args)
{
obj.Reset();
System.Threading.Thread t1 = new System.Threading.Thread(new System.Threading.ThreadStart(wirteData));
System.Threading.Thread t2 = new System.Threading.Thread(new System.Threading.ThreadStart(wirteData));
System.Threading.Thread t3 = new System.Threading.Thread(new System.Threading.ThreadStart(readData));
t1.Name = "w1";
t2.Name = "w2";
t3.Name = "r1";
t1.Start();
t2.Start();
t3.Start();
//等待输入
if (Console.ReadLine().ToLower() == "exit")
{
obj.Set();
Console.WriteLine("退出!");
}
}
//
static Random rand = new Random(100);
private static void wirteData()
{
//线程等待时间
int i = rand.Next(3000, 4000);
while (obj.WaitOne(i, false) == false)
{
Data data = new Data();
lock (stack)
{
stack.Push(data);
}
Console.WriteLine("写入:"+data.ToString());
}
Console.WriteLine("退出!");
}
private static void readData()
{
int i = rand.Next(2000, 3000);
while (obj.WaitOne(i, false) == false)
{
lock (stack)
{
if (stack.Count > 0)
{
Data data = stack.Pop() as Data;
Console.WriteLine("读取:" + data.ToString());
}
else
{
Console.WriteLine("无数据!");
}
}
}
}
}
}