c# 多线程模拟生产者消费者
2013-05-31 10:07
337 查看
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; }
}
}
相关文章推荐
- 进程同步-生产者和消费者(PV操作实现——java多线程模拟)
- Linux下多线程模拟生产者/消费者问题
- 多线程模拟生产者消费者关系
- C# 多线程编程 经典模型 生产者和消费者问题
- 多线程模拟实现生产者/消费者模型
- 多线程模拟实现生产者/消费者模型
- c#多线程之生产者与消费者问题的解决
- 多线程实例三----多生产者多消费者(模拟kfc多生产和多消费)
- 手撕代码(三)Java多线程模拟生产者消费者方法
- 多线程模拟实现生产者/消费者模型
- java多线程模拟生产者消费者问题
- C#的多线程机制探索(三)—线程的同步和通讯(生产者和消费者)
- 黑马程序员————多线程模拟:多生产者-多消费者
- 编写一个多线程程序,模拟2个生产者生产产品,3个消费者消费产品。2个生产者不停的生产商品3个消费者不停的消费产品。
- 多线程模拟实现生产者/消费者模型
- 编写一个多线程程序,模拟2个生产者生产产品,3个消费者消费产品。2个生产者不停的生产商品3个消费者不停的消费产品。
- java多线程之生产者与消费者问题的简单模拟
- 多线程模拟实现生产者/消费者模型
- 多线程模拟实现生产者/消费者模型
- 用synchonized实现多线程的消费者和生产者的模拟