对于volatile进行简单测试,提供个引子,详细的可以进一步学习。
测试代码1:using System;
using System.Threading;
namespace ConsoleApp2
{
class Program
{
///
/// 测试有无volatile的区别,在C#里无区别
///
private static int COUNTER = 0;
//private static volatile int COUNTER = 0;
static void Main(string[] args)
{
Thread th = new Thread(ChangeListener);
th.Start();
Thread th1 = new Thread(ChangeMaker);
th1.Start();
}
static void ChangeListener()
{
int threadValue = COUNTER;
while (threadValue < 5)
{
if (threadValue != COUNTER)
{
Console.WriteLine("Got Change for COUNTER : " + COUNTER + "");
threadValue = COUNTER;
}
}
Console.ReadLine();
}
static void ChangeMaker()
{
int threadValue = COUNTER;
while (COUNTER < 5)
{
Console.WriteLine("Incrementing COUNTER to : " + (threadValue + 1) + "");
COUNTER = ++threadValue;
try { Thread.Sleep(500); }
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}
}
运行结果:
using System;
namespace ConsoleApp3
{
class Program
{
///
/// 测试有无volatile 的区别,在C#里无区别
///
private static volatile int num = 0;
//private static int num = 0;
static void Main(string[] args)
{
int[] arr = new int[8000000];
for (int i = 0; i < 8000000; i++)
{
arr[i] = num;
num++;
}
Console.ReadLine();
}
}
}
运行结果:(设置断点调试)



