原始数据类型是这样的吗int
& short
Java 线程安全?我执行了以下代码,有时看不到预期结果 500。
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
value.
寻找类似的例子here http://2dayit.blogspot.in/2014/09/are-primitive-datatypes-in-java-thread.html
它们在三个方面是不安全的:
-
long
and double
甚至不能保证自动更新(您可以看到来自不同线程的一半写入)
- 内存模型不能保证您会在另一个线程中看到一个线程的最新更新,而无需某种额外的内存屏障
- 无论如何,递增变量的行为都不是原子的
Use AtomicInteger http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/atomic/AtomicInteger.html等等用于线程安全操作。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)