/**
* 1、单例范例
*/
public class Instance {
/**
* 1、volatile修饰变量,保证变量在多线程中的可见性,即:变量instance在某一线程中被更改,其它线程能立即获得修改后的值
* 2、tip:JVM运行时会有一个主内存,各线程也有各自的专属内存,
* 3、对于静态变量,如果不加volatile修饰,将由JVM自己决定何时从各线程的专属内存中读取变量值,导致脏数据出现
*/
public static volatile Instance instance = null;
/**
* synchronized修饰的方法,保证了同时只有一个线程可以调用
*/
public static synchronized Instance getInstance() {
if(instance == null) {
instance = new Instance();
}
return instance;
}
}
知识点:1、volatile 2、synchronized