生产者和消费者(.net实现)
生产者和消费者,是多线程中的经典问题,听过java方面的这个问题的培训,闲暇时用.net实现了这
个问题。在此实现的是,生产一个消息后,消费一个消息,再生产一个消息,循环往复。
1.消息代码
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ProducerAndConsumer { public class Info { private String name; public String Name { get { return name; } set { name = value; } } private String content; public String Content { get { return content; } set { content = value; } } private Boolean hasContent; public Boolean HasContent { get { return hasContent; } set { hasContent = value; } } private Object lockObj = new Object(); public Object LockObj { get { return lockObj; } } } }
2.生产者代码
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace ProducerAndConsumer { public class Producer { private Info info; public Producer(Info info) { this.info = info; } public void Produce() { for (int i = 0; i < 100; i++) { lock (info.LockObj) { if (info.HasContent) Monitor.Wait(info.LockObj); info.Name = "Name" + i; Thread.Sleep(500); info.Content = "Content" + i; Console.WriteLine("生产消息:"+this.info.Name+","+this.info.Content); info.HasContent = true; Monitor.PulseAll(info.LockObj); } } } } }
3.消费者代码
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace ProducerAndConsumer { public class Consumer { private Info info; public Consumer(Info info) { this.info = info; } public void Consume() { for (int i = 0; i < 100; i++) { lock (info.LockObj) { if (!info.HasContent) Monitor.Wait(info.LockObj); Thread.Sleep(500); Console.WriteLine("消费消息:"+this.info.Name+","+this.info.Content); info.HasContent = false; Monitor.PulseAll(info.LockObj); } } } } }
4.Main方法
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace ProducerAndConsumer { class Program { static void Main(string[] args) { Info info = new Info(); Producer pro = new Producer(info); Consumer con = new Consumer(info); Thread th1 = new Thread(new ThreadStart(pro.Produce)); Thread th2 = new Thread(new ThreadStart(con.Consume)); th1.Start(); th2.Start(); th1.Join(); th2.Join(); } } }