面试经常被问到!!!!!!
package com.company;
/**
* @Author you guess
* @Date 2021/1/29 09:32
* @Version 1.0
* @Desc 懒汉式 双重校验锁
*/
public class SingletonTest {
//变量私有
private volatile static SingletonTest instance = null;//用volatile static 修饰
//构造方法私有
private SingletonTest() {
}
//获取实例的方法 公用
public static SingletonTest getInstance() {//用static修饰方法,类可以直接调用
if (instance == null) {
synchronized (SingletonTest.class) {//类锁
if (instance == null) {
instance = new SingletonTest();
}
}
}
return instance;
}
public void test1(){
System.out.println("SingletonTest.test1");
}
}
package com.company;
/**
* @Author you guess
* @Date 2021/1/29 09:32
* @Version 1.0
* @Desc
*/
public class Main32 {
public static void main(String[] args) {
SingletonTest instance = SingletonTest.getInstance();
instance.test1();//输出 SingletonTest.test1
}
}
jdk1.8