【发布时间】:2011-08-23 21:14:40
【问题描述】:
现在,我正在学习多线程以及在 C# 中的使用。所以,我面临以下问题: (对不起我这么简单的问题)
假设,我们有两个名为 Producer 和 Consumer 的类。 Producer 任务在程序运行时产生 4 个数字,Consumer 任务正在消费并使用这些数字,并在程序结束时返回它们的总和。
消费者类定义:
class Consumer
{
private HoldInteger sharedLocation;
private Random randomSleepTime;
public Consumer(HoldInteger shared, Random random)
{
sharedLocation = shared;
randomSleepTime = random;
}
public void Consume()
{
int sum = 0;
for (int i = 1; i <= 4; i++)
{
Thread.Sleep(randomSleepTime.Next(1, 3000));
sum += sharedLocation.Buffer;
}
}
}
生产者类的定义如下:
class Producer
{
private HoldInteger sharedLocation;
private Random randomSleepTime;
public Producer(HoldInteger shared, Random random)
{
sharedLocation = shared;
randomSleepTime = random;
}
public void Produce()
{
for (int i = 1; i <= 4; i++)
{
Thread.Sleep(randomSleepTime.Next(1, 3000));
sharedLocation.Buffer = i;
}
}
}
而且,我们有HoldInteger 类包含缓冲区变量,生产者写入此变量,消费者从中读取。我结合这些类并在我的 main 方法中编写以下代码:
static void Main(string[] args)
{
HoldInteger holdInteger = new HoldInteger();
Random random = new Random();
Producer producer = new Producer(holdInteger, random);
Consumer consumer = new Consumer(holdInteger, random);
Thread producerThread = new Thread(new ThreadStart(producer.Produce));
producerThread.Name = "producer";
Thread consumerThread = new Thread(new ThreadStart(consumer.Consume));
consumerThread.Name = "consumer";
producerThread.Start();
consumerThread.Start();
}
所以,我的问题是How can i manage this relationship With Low Memory and Time Wasting ?
请注意,这些线程管理代码将放在HoldInteger类体中。
感谢您的关注。
【问题讨论】:
标签: c# .net multithreading synchronization circular-buffer