public class Cell
{
int cellContents;
bool readerFlag = false;
public int ReadFromCell( )
{
lock(this) // 这里的lock是锁定这个Cell类只能同时被1个线程运行对吗?
{
if (!readerFlag)
{
try
{
Monitor.Wait(this);//这里我不太明白,是释放被lock锁定的Cell类好让另外的线程运行吗?
}
catch (SynchronizationLockException e)
{
Console.WriteLine(e);
}
catch (ThreadInterruptedException e)
{
Console.WriteLine(e);
}
}
Console.WriteLine("Consume: {0}",cellContents);
readerFlag = false;
Monitor.Pulse(this);//这里也不明白,msdn的解释是,通知等待队列中的线程锁定对象状态的更改,可我不明白,他是通知别的线程被当前线程锁定的Cell类已经被释放?他是否执行了释放?执行释放不是Monitor.Exit吗?
}
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);
}
}
}
{
int cellContents;
bool readerFlag = false;
public int ReadFromCell( )
{
lock(this) // 这里的lock是锁定这个Cell类只能同时被1个线程运行对吗?
{
if (!readerFlag)
{
try
{
Monitor.Wait(this);//这里我不太明白,是释放被lock锁定的Cell类好让另外的线程运行吗?
}
catch (SynchronizationLockException e)
{
Console.WriteLine(e);
}
catch (ThreadInterruptedException e)
{
Console.WriteLine(e);
}
}
Console.WriteLine("Consume: {0}",cellContents);
readerFlag = false;
Monitor.Pulse(this);//这里也不明白,msdn的解释是,通知等待队列中的线程锁定对象状态的更改,可我不明白,他是通知别的线程被当前线程锁定的Cell类已经被释放?他是否执行了释放?执行释放不是Monitor.Exit吗?
}
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);
}
}
}
至于Monitor类的使用我也搞不清楚,只知道Enter和Exit使用,Wait和Pulse使用