我试图了解 volatile 关键字的用法,所以我写了一个小例子,我想使用 Volatile 关键字,但目前我得到相同的行为,要么我使用 Volatile 关键字,要么我不使用它。
以下是我正在运行的代码,我希望线程 t2 继续执行,即使 t1 正在更新 ExitLoop 属性
namespace UsageOfVolatileKeyword
{
class Program
{
static void Main()
{
Test t = new Test();
Thread t2 = new Thread(() => { while (!t.ExitLoop) { Console.WriteLine("In loop"); } });
t2.Start();
Thread t1 = new Thread(() => t.ExitLoop = true);
t1.Start();
t2.Join();
Console.WriteLine("I am done");
Console.ReadLine();
}
}
class Test
{
private bool _exitLoop = false; //I am marking this variable as volatile.
public bool ExitLoop
{
get { return _exitLoop; }
set { _exitLoop = value; }
}
}
}
如果有人能帮助我理解我做错了什么以及 Volatile 关键字的正确用法是什么,那就太好了。