现在,我正在学习多线程以及在 C# 中的使用。所以,我面临以下问题:(对不起我这么简单的问题)
假设,我们有两个名为 Producer 和 Consumer 的类。生产者任务在程序运行时产生 4 个数字,消费者任务正在消费并使用这些数字,并在程序结束时返回它们的总和。
消费者类定义:
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
包含 Buffer 变量的类,生产者写入这个变量,消费者从中读取。我结合这些类并在我的主要方法中编写以下代码:
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
类体中。
感谢您的关注。