標籤:c# 生產者 消費者
生產者類:
public class Producer
{
ArrayList container = null;
//得到一個容器
public Producer(ArrayList container)
{
this.container = container;
}
//定義一個生產物品的方法裝入容器
public void Product(string name)
{
//建立一個新物品裝入容器
Goods goods = new Goods();
goods.Name = name;
this.container.Add(goods);
Console.WriteLine("生產了物品:" + goods.ToString());
}
}
消費者類:
public void Consumption()
{
Goods goods = (Goods)this.container[0];
Console.WriteLine("消費了物品:" + goods.ToString());
//消費掉容器中的一個物品
this.container.RemoveAt(0);
}
}
食物類:
public class Goods
{
//物品名稱
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
//重寫ToString()
public override string ToString()
{
return "物品名稱:" + name;
}
}
主程式:
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Threading;
namespace ConsoleApplication1
{
class Program
{
ArrayList container = new ArrayList();
Producer producer = null;
Consumer consumer = null;
static void Main(string[] args)
{
Program p = new Program();
//建立兩個線程並啟動
Thread t1 = new Thread(new ThreadStart(p.ThreadProduct));
Thread t2 = new Thread(new ThreadStart(p.ThreadConsumption));
t1.Start();
//t1.Sleep(1);
t2.Start();
Console.Read();
}
//定義一個線程方法生產8個物品
public void ThreadProduct()
{
//建立一個生產者
producer = new Producer(this.container);
lock (this) //防止因爭奪資源而造成互相等待 {
for (int i = 1; i <= 8; i++)
{
//如果容器中沒有就進行生產
if (this.container.Count == 0)
{
//調用方法進行生產
producer.Product(i + "");
//生產好了一個通知消費者消費
Monitor.Pulse(this);
}
//容器中還有物品等待消費者消費後再生
Monitor.Wait(this);
}
}
}
//定義一個線程方法消費生產的物品
public void ThreadConsumption()
{
//建立一個消費者
consumer = new Consumer(this.container);
lock (this)//防止因爭奪資源而造成互相等待 {
while (true)
{
//如果容器中有商品就進行消費
if (this.container.Count != 0)
{
//調用方法進行消費
consumer.Consumption();
Monitor.Pulse(this);
}
//容器中沒有商品通知消費者消費
Monitor.Wait(this);
}
}
}
}
}
生產者消費者問題(C#)