原始數據類型是int
& short
在Java中是線程安全的嗎?我執行了下面的代碼,有些時候看不到預期的結果500。原始數據類型在Java中是線程安全的
public class SampleThree extends Thread
{
static long wakeUpTime = System.currentTimeMillis() + (1000*20);
static int inT;
public static void main(String args[])
{
System.out.println("initial:" + inT);
for(int i=0; i<500; i++)
new SampleThree().start();
try {
Thread.sleep(wakeUpTime - System.currentTimeMillis() + (1000*30));
System.out.println("o/p:" + inT);
}
catch(Exception e){
e.printStackTrace();
}
}
public void run()
{
try {
long s = wakeUpTime - System.currentTimeMillis();
System.out.println("will sleep ms: " + s);
Thread.sleep(s);
inT++; // System.out.println(inT);
}
catch(Exception e) {
e.printStackTrace();
}
}
}
這裏同時有500個線程將更新int變量inT
。主線程等待併發更新完成後,打印inT
值。
找到類似的例子here
不,它們不是線程安全的。如果你只打算閱讀,你應該考慮讓成員變成「volatile」。如果你打算從不同的線程讀取和寫入它,你應該使它成爲'同步的' – 2012-02-14 14:41:34