从 C# 通过 CLR 书:通过引用和值类型进行同步
From C# via CLR book: synchronization by reference and value types
拜托,你认为控制台中会出现什么输出(有点琐事):
按引用类型同步:
class Program
{
static int x = 8;
static object obj = new object();
static void Main(string[] args)
{
Thread t1 = new Thread(new ThreadStart(f1));
Thread t2 = new Thread(new ThreadStart(f1));
Thread t3 = new Thread(new ThreadStart(f1));
Thread t4 = new Thread(new ThreadStart(f1));
t1.Start();
t2.Start();
t3.Start();
t4.Start();
Console.ReadLine();
}
private static void f1()
{
Monitor.Enter(obj);
x++;
Thread.Sleep(3000);
Console.WriteLine(x);
Monitor.Exit(obj);
}
}
按值类型同步:
class Program
{
static int x = 8;
static int y = 444;
static void Main(string[] args)
{
Thread t1 = new Thread(new ThreadStart(f1));
Thread t2 = new Thread(new ThreadStart(f1));
Thread t3 = new Thread(new ThreadStart(f1));
Thread t4 = new Thread(new ThreadStart(f1));
t1.Start();
t2.Start();
t3.Start();
t4.Start();
Console.ReadLine();
}
private static void f1()
{
Monitor.Enter(y);
x++;
Thread.Sleep(3000);
Console.WriteLine(x);
Monitor.Exit(y);
}
}
在我的脑海中(你说的是琐事),我会说 Monitor.Enter(int) 将收到 y 的盒装副本,因此你将锁定四个不同的对象而不是一,使锁失效。
顺便说一句,这不是个好问题。您应该问 为什么 它没有按您预期的方式工作。
拜托,你认为控制台中会出现什么输出(有点琐事):
按引用类型同步:
class Program
{
static int x = 8;
static object obj = new object();
static void Main(string[] args)
{
Thread t1 = new Thread(new ThreadStart(f1));
Thread t2 = new Thread(new ThreadStart(f1));
Thread t3 = new Thread(new ThreadStart(f1));
Thread t4 = new Thread(new ThreadStart(f1));
t1.Start();
t2.Start();
t3.Start();
t4.Start();
Console.ReadLine();
}
private static void f1()
{
Monitor.Enter(obj);
x++;
Thread.Sleep(3000);
Console.WriteLine(x);
Monitor.Exit(obj);
}
}
按值类型同步:
class Program
{
static int x = 8;
static int y = 444;
static void Main(string[] args)
{
Thread t1 = new Thread(new ThreadStart(f1));
Thread t2 = new Thread(new ThreadStart(f1));
Thread t3 = new Thread(new ThreadStart(f1));
Thread t4 = new Thread(new ThreadStart(f1));
t1.Start();
t2.Start();
t3.Start();
t4.Start();
Console.ReadLine();
}
private static void f1()
{
Monitor.Enter(y);
x++;
Thread.Sleep(3000);
Console.WriteLine(x);
Monitor.Exit(y);
}
}
在我的脑海中(你说的是琐事),我会说 Monitor.Enter(int) 将收到 y 的盒装副本,因此你将锁定四个不同的对象而不是一,使锁失效。
顺便说一句,这不是个好问题。您应该问 为什么 它没有按您预期的方式工作。