实例代码:主要是lock防止池在同一时间被其它线程占用
//假设这个类型的对象创建起来比较耗时
public class TimeConsumeConnection
{
}
internal class Program
{
private static readonly object Sync = new object();
private static void Main(string[] args)
{
//假设一个池
TimeConsumeConnection[] conPool = new TimeConsumeConnection[100];
//声明一个变量来维护当前池中的对象的个数。
int count = 0;
//生产者,假设5个线程同时在进行“生产”→创建对象并加入到conPool池中
for (int i = 0; i < 5; i++)
{
//没循环一次创建一个线程
Thread t = new Thread(() =>
{
//不断的生产对象并加入到conPool池中
while (true)
{
lock (Sync)
{
if (count < conPool.Length)
{
//创建一个Connection对象并把该对象加到conPool池中
TimeConsumeConnection connection = new TimeConsumeConnection();
conPool[count] = connection;
count++;
Console.WriteLine("生产了一个对象。");
}
}
Thread.Sleep(300);
}
})
{ IsBackground = true };
t.Start();
}
//消费者假设有10个消费者,从池中获取对象并使用
for (int i = 0; i < 10; i++)
{
Thread t = new Thread(() =>
{
while (true)
{
lock (Sync)
{
//在消费对象前,要判断一下池中是否有可用对象
if (count > 0)
{
TimeConsumeConnection con = conPool[count - 1];
Console.WriteLine("使用该对象:" + con);
conPool[count - 1] = null;
count--;
}
}
Thread.Sleep(50);
}
})
{ IsBackground = true };
t.Start();
}
Console.ReadKey();
}
}