这周在学习多线程,CLR via C# 3 Edition结合网上资料,很是不亦乐乎,一个小时前在知识库又发现一些多线程的好例子,自己实现了一遍,保存下来; PS:说实话cnblogs知识库真的是不错,个人感觉就是分类稍微有点粗,不过比首页好多了,首页基本遇不到自己想要的东西和适合自己的东东,好多时候也是一些“谈谈哥”和“也谈谈哥”在扯蛋;
重在保存,只有代码,可以去原文查看详细(用多线程实现了消费者和生产者的模式,线程间的同步,有点类似于操作系统里面的p/v操作)
代码namespace Alex.MultiThread
{
public class Cell
{
int cellContents;
bool readerFlag=false;
public int ReadFromCell()//读(消费)
{
lock (this)
{
if (!readerFlag)
{
try
{
Monitor.Wait(this);
}
catch (SynchronizationLockException e)
{
Console.WriteLine(e);
}
catch (ThreadInterruptedException e)
{
Console.WriteLine(e);
}
}
Console.WriteLine("Consume:{0}", cellContents);
readerFlag =false;
Monitor.Pulse(this);
}
return cellContents;
}
public void WriteToCell(int n)//写(生产)
{
lock (this)
{
if (readerFlag)
{
try
{
Monitor.Wait(this);
}
catch (SynchronizationLockException e)
{
Console.WriteLine(e);
}
catch (ThreadInterruptedException e)
{
Console.WriteLine(e);
}
}
cellContents = n;
Console.WriteLine("Produce:{0}", cellContents);
readerFlag =true;
Monitor.Pulse(this);
}
}
}
///
<summary>
/// 生产者
///
</summary>
public class CellProd
{
Cell cell;
int quantity=
1;//生产者生产次数
public CellProd(Cell cell,int request)
{
this.cell= cell;
quantity = request;
}
public void ThreadRun()
{
for(int looper=1;looper<=quantity;looper++)
{
cell.WriteToCell(looper);//生产
}
}
}
///
<summary>
/// 消费者
///
</summary>
public class CellCons
{
Cell cell;
int quantity=1;
public CellCons(Cell cell,int request)
{
this.cell= cell;
quantity = request;
}
public void ThreadRun()
{
for(int looper=1;looper<=quantity;looper++)
{
cell.ReadFromCell();//消费
}
}
}
public class MonitorSample
{
public staticvoid Main()
{
int result=0;//标志位,0表示程序没有出错,1表示出错
Cell cell =new Cell();
CellProd prod =new CellProd(cell,20);
CellCons cons =new CellCons(cell,20);
Thread producer =new Thread(new ThreadStart(prod.ThreadRun));
Thread consumer =new Thread(new ThreadStart(cons.ThreadRun));
try
{
producer.Start();
consumer.Start();
producer.Join();
consumer.Join();
Console.ReadLine();
}
catch (ThreadStartException e)
{
Console.WriteLine(e);
result =1;
}
catch (ThreadInterruptedException e)
{
Console.WriteLine(e);
result =1;
}
Environment.ExitCode = result;
}
}
}
多线程--C#利用多线程实现消费者和生产者模式
最新推荐文章于 2020-05-05 15:18:07 发布