volatile并不能保证多个线程共同修改 代码块的代码 时所带来的不一致问题,也就是说volatile不能替代synchronized
volitile 只能保证可见性不能保证原子性,即替代不了synchronized
import java.util.ArrayList;
import java.util.List;
public class VolatileVsSync {
volatile int count = 0;
void m() {
for (int i = 0; i < 10000; i++)
count++;
}
public static void main(String[] args) {
VolatileVsSync t = new VolatileVsSync();
List<Thread> threads = new ArrayList<Thread>();
for (int i = 0; i < 10; i++) {
threads.add(new Thread(t::m, "thread-" + i));
}
threads.forEach((o) -> o.start());
threads.forEach((o) -> {
try {
o.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
System.out.println(t.count);
}
}
执行结果<10000*10 ,所以需要将方法m上加上synchronized关键字,volatile可以省略
注意:volitile 保证数据的可见性,只有引用本身改了其它线程才能监测到
使用原则,如果没把握不要用,修饰的话要修饰简单类型,不要修饰引用类型,因为引用不变,引用的指向的属性值变化是监测不到的