我有一個由兩個線程共享的變量。這兩個線程將對其執行一些操作。我不知道爲什麼每次執行程序時sharedVar的結果都不一樣。同步方法不能按預期方式工作
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,這是我期望的結果。該計劃的另一個有趣的事情是時間= 1000。作爲最終結果,我總是得到2000。
任何人都可以解釋這種現象嗎?
嘗試使sharedVar揮發性。 –
將volatile添加到sharedVar後,結果接近20000,但仍低於20000. – Brian
易失性單獨無法工作的原因是因爲'Main.sharedVar ++'是一個複合操作(read-increment-write)。揮發性不提供任何保護。 – Kayaman