using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace TestThread
{
class Program
{
private static Queue<int> data_int = new Queue<int>();
private static Mutex mtx = new Mutex();
private static int i = 0;
private static void write()
{
while (true)
{
try
{
Monitor.Enter(mtx);
data_int.Enqueue(i);
Console.WriteLine("write:"+i);
i++;
}
finally
{
Monitor.Exit(mtx);
}
Monitor.Pulse(mtx);
Thread.Sleep(30000);//模拟外部数据,1秒获得一次
}
}
private static void read()
{
while (true)
{
try
{
Monitor.Enter(mtx);
bool hasData = data_int.Count > 0;
if(!hasData)
{
Monitor.Wait(mtx, -1, false);
}
if (data_int.Count > 0)
{
int i = data_int.Dequeue();
Console.WriteLine("read"+i);
}
}
finally
{
Monitor.Exit(mtx);
}
}
}
static void Main(string[] args)
{
Thread read1 = new Thread(read);
read1.Name = "read1";
read1.Start();
Thread read2 = new Thread(read);
read2.Name = "read2";
read2.Start();
Thread write1 = new Thread(write);
write1.Name = "write1";
write1.Start();
//Thread write2 = new Thread(write);
//write2.Start();
}
}
}