我有一个变量,由两个线程共享。这两个线程会在它上面进行一些操作。但每次执行程序时,共享变量的结果不同,我不知道为什么。
public class Main
{
public static int sharedVar = 0;
public static void main(String[] args)
{
MyThread mt1 = new MyThread();
MyThread mt2 = new MyThread();
mt1.start();
mt2.start();
try
{
// wait for the threads
mt1.join();
mt2.join();
}
catch (InterruptedException e1)
{
e1.printStackTrace();
}
System.out.println(sharedInt); // I expect this value to be 20000, but it's not
}
}
以下是 "MyThread" 类:
public class MyThread extends Thread
{
private int times = 10000;
private synchronized void addOne()
{
for (int i = 0; i < times; ++i)
{
Main.sharedVar ++;
}
}
@Override
public void run()
{
addOne();
}
}
有时候,sharedVar的最终结果会是13735、12508或18793,但从未达到我期望的20000。另一个有趣的现象是当times=1000时,最终结果总是2000。
有人能解释这种现象吗?
Main.sharedVar++
是一个复合操作(读取-增加-写入)。Volatile 对此没有保护作用。 - Kayaman