using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace 多线程模拟生产者消费者
{
class Program
{
static void Main(string[] args)
{
MyObject[] objectPool = new MyObject[10];
int index = 0;
object oLock = new object();
//定义5个生成者
for (int i = 0; i < 10; i++)
{
Thread thread = new Thread(() =>
{
while (true)
{
lock (oLock)
{
if (index > 9)
{
continue;
}
MyObject myObject = new MyObject();
objectPool[index] = myObject;
Console.WriteLine("生产了一个对象Index:{0},线程ID{1}",
index,Thread.CurrentThread.ManagedThreadId);
if (index < 10)
{
index++;
}
Thread.Sleep(100);
}
}
}
);
thread.IsBackground = true;
thread.Start();
}
//生产10个消费者
for (int i = 0; i < 0; i++)
{
Thread thread = new Thread(() =>
{
while (true)
{
lock (oLock)
{
if (index < 0)
{
continue;
}
objectPool[index] = null;
Console.WriteLine("消费了一个对象Index:{0},线程ID{1}",
index, Thread.CurrentThread.ManagedThreadId);
if (index > 0)
{
index--;
}
Thread.Sleep(100);
}
}
}
);
thread.IsBackground = true;
thread.Start();
}
Console.WriteLine("达到最大Index:{0},线程ID{1}",
index, Thread.CurrentThread.ManagedThreadId);
Console.ReadKey();
}
}
public class MyObject
{
public string Name { get; set; }
}
}
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace 多线程模拟生产者消费者
{
class Program
{
static void Main(string[] args)
{
MyObject[] objectPool = new MyObject[10];
int index = 0;
object oLock = new object();
//定义5个生成者
for (int i = 0; i < 10; i++)
{
Thread thread = new Thread(() =>
{
while (true)
{
lock (oLock)
{
if (index > 9)
{
continue;
}
MyObject myObject = new MyObject();
objectPool[index] = myObject;
Console.WriteLine("生产了一个对象Index:{0},线程ID{1}",
index,Thread.CurrentThread.ManagedThreadId);
if (index < 10)
{
index++;
}
Thread.Sleep(100);
}
}
}
);
thread.IsBackground = true;
thread.Start();
}
//生产10个消费者
for (int i = 0; i < 0; i++)
{
Thread thread = new Thread(() =>
{
while (true)
{
lock (oLock)
{
if (index < 0)
{
continue;
}
objectPool[index] = null;
Console.WriteLine("消费了一个对象Index:{0},线程ID{1}",
index, Thread.CurrentThread.ManagedThreadId);
if (index > 0)
{
index--;
}
Thread.Sleep(100);
}
}
}
);
thread.IsBackground = true;
thread.Start();
}
Console.WriteLine("达到最大Index:{0},线程ID{1}",
index, Thread.CurrentThread.ManagedThreadId);
Console.ReadKey();
}
}
public class MyObject
{
public string Name { get; set; }
}
}