我们在开发过程中经常会遇到需要从一个地方不断获取数据然后又需要交给另一个线程对数据进行二次加工的情况,这种场景适合使用生产者-消费者模式。
Demo展示
//中间的容器
public static class Container
{
public static Queue<string> StringTemp = new Queue<string>();
}
/// <summary>
/// 生产者
/// </summary>
public class Producer
{
Queue<string> StringContainer = new Queue<string>();
public Producer(Queue<string> container)
{
this.StringContainer = container;
}
public void Produce()
{
StringContainer.Enqueue("i");
}
}
/// <summary>
/// 消费者
/// </summary>
public class Consumer
{
Queue<string> StringContainer = new Queue<string>();
public Consumer(Queue<string> container)
{
this.StringContainer = container;
}
public void Consume()
{
var key = StringContainer.Dequeue();
Console.WriteLine("{0},你好,当前线程ID为{1}" ,key, Thread.CurrentThread.ManagedThreadId.ToString());
}
}
class Program
{
readonly static object _locker = new object();
static void Main(string[] args)
{
//生产者消费者模式
//开启生产
Action<string> produce = Product;
produce.BeginInvoke("", null, null);
//开启消费
Action<string> consume = Consume;
consume.BeginInvoke("", null, null);
//开启消费2
Action<string> consume2 = Consume;
consume2.BeginInvoke("", null, null);
Console.ReadLine();
}
/// <summary>
/// 生产
/// </summary>
/// <param name="name"></param>
static void Product(string name)
{
while (true)
{
Thread.Sleep(2000);
lock (_locker)
{
if (Container.StringTemp.Count == 0)
{
new Producer(Container.StringTemp).Produce();
}
else {
Console.WriteLine("生产者没有任务"+Thread.CurrentThread.ManagedThreadId.ToString());
}
}
}
}
/// <summary>
/// 消费
/// </summary>
/// <param name="name"></param>
static void Consume(string name)
{
while (true)
{
Thread.Sleep(1000);
lock (_locker)
{
if (Container.StringTemp.Count > 0)
{
new Consumer(Container.StringTemp).Consume();
}
else {
Console.WriteLine("消费者没有任务" + Thread.CurrentThread.ManagedThreadId.ToString());
}
}
}
}
}
运行效果如下图:
|
请发表评论