做操作系统课设的时候使用的基本代码。
- using
System; - using
System.Collections.Generic; - using
System.Text; - using
System.Collections; - using
System.Threading; - namespace
ConsoleApplication4 - {
-
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(); -
t2.Start(); -
Console.Read(); -
} -
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); -
} -
} -
} -
} -
public class Consumer -
{ -
ArrayList container = null; -
public Consumer(ArrayList container) -
{ -
this.container = container; -
} -
public void Consumption() -
{ -
Goods goods = (Goods)this.container[0]; -
Console.WriteLine("消费了物品:" + goods.ToString()); -
this.container.RemoveAt(0); -
} -
} -
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 class Goods -
{ -
private string name; -
public string Name -
{ -
get { return name; } -
set { name = value; } -
} -
public override string ToString() -
{ -
return "物品名称:" + name; -
} -
} - }
版权声明:本文为wk360833257原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。