public class Test {
private static AtomicInteger count= new AtomicInteger(0);
public static void main(String[] args) throws InterruptedException{
for(int i=0;i<10000;i++){
new Thread(new Runnable() {
@Override
public void run() {
add();
}
}).start();
}
Thread.sleep(1000);
System.out.println(Test.count);
}
public static void add(){
count.incrementAndGet();
}
}
输出是10000,
public class Test {
private static int count= 0;
public static void main(String[] args) throws InterruptedException{
for(int i=0;i<10000;i++){
new Thread(new Runnable() {
@Override
public void run() {
add();
}
}).start();
}
Thread.sleep(1000);
System.out.println(Test.count);
}
public static void add(){
count++;
}
}
数据结果不确定
同样的++i也是同样的效果
如果count 用volatile修饰的话同样也是能够打印10000;
结论
- volatile解决了线程间共享变量的可见性问题
- 使用volatile会增加性能开销
- volatile并不能解决线程同步问题
- 解决i++或者++i这样的线程同步问题需要使用synchronized或者AtomicXX系列的包装类,同时也会增加性能开销