using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace M_生产者消费者模式 { class Program { static void Main(string[] args) { Prodeuct[] produs=new Prodeuct[100]; object m_lock=new object(); int index = 0; //定义5个生产者 for(int i =0;i<5;i++) { new Thread(() => { while (true) { lock (m_lock) { if (index < 99) { Prodeuct p = new Prodeuct(); produs[index] = p; Console.WriteLine("生成一个产品" + Thread.CurrentThread.ManagedThreadId); index++; } } } }).Start(); //定义5个消费者 for (int j = 0; j < 5; j++) { new Thread(() => { while (true) { lock (m_lock) { if (index > 0) { Prodeuct p = produs[index - 1] = null; Console.WriteLine("消耗一个产品" + Thread.CurrentThread.ManagedThreadId); index--; } } Thread.Sleep(100); } }).Start(); } } } public class Prodeuct { } } }