您的位置:首页 > 编程语言 > C#

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; }

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: