消费者与生产者
来源:互联网 发布:js获取 鼠标位置 编辑:程序博客网 时间:2024/06/05 18:07
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ProductCreate
{
class Program
{
static void Main(string[] args)
{
//定义了一个对象池:最大个数是100个。
Product[] ProductPool =new Product[100];
int index = 0;//以上来消费到0。现在没有产品
object objLock = new object();
//初始化10个消费者
for (int i = 0; i < 10; i++)
{
Thread thread =new Thread(() =>
{
while (true)//不停的消费
{
//只要锁同一个对象那么就会互斥。
lock (objLock)//锁住对象:objLock。同一时间只能有一个线程获得此对象的锁。
{
if (index > 0)
{
ProductPool[index - 1] = null;
index--;
Console.WriteLine("消费一个产品");
}
}//lock的花括号执行完成。对象锁被释放。
Thread.Sleep(30);
}
});
thread.IsBackground = true;
thread.Start();
}
//初始化3个生成者
//初始化10个消费者
for (int i = 0; i < 3; i++)
{
Thread thread = new Thread(() =>
{
while (true)//不停的消费
{
lock (objLock)
{
if (index < 100)
{
ProductPool[index] = new Product() { Id = 0, ProName = DateTime.Now.ToString() };
index++;
Console.WriteLine("生成一个产品");
}
}
Thread.Sleep(30);
}
});
thread.IsBackground = true;
thread.Start();
}
Console.ReadKey();
}
}
public class Product
{
public int Id { get; set; }
public string ProName { get; set; }
}
}
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ProductCreate
{
class Program
{
static void Main(string[] args)
{
//定义了一个对象池:最大个数是100个。
Product[] ProductPool =new Product[100];
int index = 0;//以上来消费到0。现在没有产品
object objLock = new object();
//初始化10个消费者
for (int i = 0; i < 10; i++)
{
Thread thread =new Thread(() =>
{
while (true)//不停的消费
{
//只要锁同一个对象那么就会互斥。
lock (objLock)//锁住对象:objLock。同一时间只能有一个线程获得此对象的锁。
{
if (index > 0)
{
ProductPool[index - 1] = null;
index--;
Console.WriteLine("消费一个产品");
}
}//lock的花括号执行完成。对象锁被释放。
Thread.Sleep(30);
}
});
thread.IsBackground = true;
thread.Start();
}
//初始化3个生成者
//初始化10个消费者
for (int i = 0; i < 3; i++)
{
Thread thread = new Thread(() =>
{
while (true)//不停的消费
{
lock (objLock)
{
if (index < 100)
{
ProductPool[index] = new Product() { Id = 0, ProName = DateTime.Now.ToString() };
index++;
Console.WriteLine("生成一个产品");
}
}
Thread.Sleep(30);
}
});
thread.IsBackground = true;
thread.Start();
}
Console.ReadKey();
}
}
public class Product
{
public int Id { get; set; }
public string ProName { get; set; }
}
}
- 生产者与消费者问题
- 生产者与消费者
- 生产者与消费者
- 生产者与消费者问题
- 消费者与生产者模式
- 消费者与生产者模式
- 消费者与生产者模式
- 生产者与消费者问题
- 生产者与消费者
- 生产者与消费者
- 生产者与消费者
- 生产者与消费者问题
- C# 生产者与消费者
- 生产者与消费者
- 生产者与消费者--一对一
- 死锁,生产者与消费者
- 生产者与消费者模型
- java 生产者与消费者
- cocos2d-x节点(CCParticleBatchNode.h)API
- cocos2d-x节点(CCParticleSystem.h)API
- cocos2d-x节点(CCParticleSystemQuad.h)API
- MyEclipse的服务器配置
- Android开发入门自结
- 消费者与生产者
- 密码学学习(二) 置换加密算法(Transposition Cipher)及python实现
- 每日随笔131117
- 第11周任务
- IPC进程间通信
- 程序员:下一次面试前你需要准备的五个基本步骤
- C++必知必会之(5)引用是别名而非指针
- 黑马程序员 多线程
- Opengl中导入obj文件