using System;
using System.Threading;
public class SyncExample
{
public static void Main()
{
Data dt = new Data();
Producer p = new Producer(dt);
Consumer c = new Consumer(dt);
Thread pt = new Thread(new ThreadStart(p.run));
Thread ct = new Thread(new ThreadStart(c.run));
pt.Start();
ct.Start();
}
}
public class Producer
{
private Data data;
public Producer(Data data)
{
this.data = data;
}
public void run()
{
while (true)
{
data.produce();
Thread.Sleep(1000);
}
}
}
public class Consumer
{
private Data data;
public Consumer(Data data)
{
this.data = data;
}
public void run()
{
while (true)
{
data.consume();
Thread.Sleep(1000);
}
}
}
public class Data
{
public int value=0;
public bool isReady = false;
public void produce()
{
lock(this)
{
if (isReady)
Monitor.Wait(this);
value++;
Console.WriteLine("Produced:"+value);
isReady = true;
Monitor.Pulse(this);
}
}
public void consume()
{
lock(this)
{
if (!isReady)
Monitor.Wait(this);
Console.WriteLine("Consumed:"+value);
isReady = false;
Monitor.Pulse(this);
}
}
}