class Program
{
private static volatile int value;
public static void Increment()
{
for (int i =0; i <100000; i++)
{
value++;
}
}
public static void Decrement()
{
for (int j =0 ; j < 100000; j++)
{
value--;
}
}
public static void ThreadTest()
{
value = 0;
var incrementThread = new Thread(Increment);
var decrementThread = new Thread(Decrement);
incrementThread.Start();
decrementThread.Start();
incrementThread.Join();
decrementThread.Join();
Console.WriteLine("Value of value {0}", value);
}
static void Main(string[] args)
{
ThreadTest();
}
}
Run Code Online (Sandbox Code Playgroud)
Ale*_*kov 17
因为它不应该...... ++和 - 不是原子操作(不像Interlocked.XXXX opreations - Interlocked.Increment).
如果你写下++的每一步,并且 - 看看两者如何通过不同的线程混合,你就会明白为什么:
增量
1: load value to temp
2: add temp, 1
3: store temp to value
Run Code Online (Sandbox Code Playgroud)
减量
4: load value to temp2
5: substruct temp2, 1
6: store temp2 to value
Run Code Online (Sandbox Code Playgroud)
因此,如果订单是1,2,3,4,5,6,则得到值= 0; 但如果订单是1,2,4,5,6,3,则得到值= 1.