请看下面的代码。我正在了解 C# 中的多线程。该示例取自一些手册。在我的 Main 函数中,我尝试创建三个线程。
您能否告诉我应该如何正确创建两个线程(有错误)?
谢谢!
using System;
using System.Threading;
public static class MonitorMethodAccess
{
private static int numericField = 1;
private static object syncObj = new object();
public static object SyncRoot
{
get { return syncObj; }
}
public static void IncrementNumericField()
{
if (Monitor.TryEnter(syncObj, 250))
{
try
{
++numericField;
}
finally
{
Monitor.Exit(syncObj);
}
}
}
public static void ModifyNumericField(int newValue)
{
if (Monitor.TryEnter(syncObj, 250))
{
try
{
numericField = newValue;
}
finally
{
Monitor.Exit(syncObj);
}
}
}
public static int ReadNumericField()
{
if (Monitor.TryEnter(syncObj, 250))
{
try
{
return (numericField);
}
finally
{
Monitor.Exit(syncObj);
}
}
return (-1);
}
}
class Program
{
static void Main(string[] args)
{
Thread aaa = new Thread(MonitorMethodAccess.IncrementNumericField);
Thread bbb = new Thread(MonitorMethodAccess.ModifyNumericField(12);//error
Thread ccc = new Thread(MonitorMethodAccess.ReadNumericField);//error
Console.ReadKey();
}
}