using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Collections;
namespace ConAppThread
{
class Program
{
protected const int MAX_LAN = 5;
//定义缓冲池
ArrayList arr = new ArrayList();
static void Main(string[] args)
{
Program obj = new Program();
while (true)
{
//定义生产者线程
Thread pro0 = new Thread(new ThreadStart(obj.Producer));
Thread pro1 = new Thread(new ThreadStart(obj.Producer));
Thread pro2 = new Thread(new ThreadStart(obj.Producer));
Thread pro3 = new Thread(new ThreadStart(obj.Producer));
//定义消费者线程
Thread con4 = new Thread(new ThreadStart(obj.Consumer));
Thread con5 = new Thread(new ThreadStart(obj.Consumer));
Thread con6 = new Thread(new ThreadStart(obj.Consumer));
Thread con7 = new Thread(new ThreadStart(obj.Consumer));
//随机调用生产者与消费者线程
switch (obj.GetRandom(8).ToString())
{
case "0":
//启动生产者线程0
pro0.Start();
Thread.Sleep(200);
break;
case "1":
//启动生产者线程1
pro1.Start();
Thread.Sleep(200);
break;
case "2":
//启动生产者线程2
pro2.Start();
Thread.Sleep(200);
break;
case "3":
//启动生产者线程3
pro3.Start();
Thread.Sleep(200);
break;
case "4":
//启动消费者线程4
con4.Start();
Thread.Sleep(200);
break;
case "5":
//启动消费者线程5
con5.Start();
Thread.Sleep(200);
break;
case "6":
//启动消费者线程6
con6.Start();
Thread.Sleep(200);
break;
case "7":
//启动消费者线程7
con7.Start();
Thread.Sleep(200);
break;
}
}
}
//生产者
public void Producer()
{
Monitor.Enter(this);
if (IsFull())
Console.Out.WriteLine("数据池满,不能增加数!");
else
{
//产生0-1000的随机整数放入缓冲池arr中
int x = GetRandom(1000);
Console.Out.WriteLine("增加数 {0}: ", x.ToString());
arr.Add(x);
}
Monitor.Exit(this);
}
//消费者
public void Consumer()
{
Monitor.Enter(this);
if (IsEmpty())
Console.Out.WriteLine("数据池空,不能取出数!");
else
{
//产生arr的随机下标
int n = GetRandom(arr.Count);
Console.Out.WriteLine("取出数 {0}: ", arr[n].ToString());
arr.Remove(arr[n]);
}
Monitor.Exit(this);
}
//输出缓冲池中的数
public void ArrNumShow()
{
foreach (int x in arr)
{
Console.Out.WriteLine(x);
}
}
//产生随机数
public int GetRandom(int intNum)
{
Random random = new Random();
return random.Next(intNum);
}
//判断缓冲池是否为空
public bool IsEmpty()
{
if (arr.Count == 0)
return true;
else
return false;
}
//判断缓冲池是否为满
public bool IsFull()
{
if (arr.Count == MAX_LAN)
return true;
else
return false;
}
}
}
//不知道为什么把线程的定义放while循环的外面就不可以了。