/**
* @author: Lei
* @Description:
* @date: 2022/5/13
* 优点:编写简单
* 缺点;加载类的时候就会实例化
* jvm实现的线程安全
**/
@SpringBootTest
public class Singleton {//饿汉式
private static final Singleton INSTANCE = new Singleton();
private Singleton(){}
@Test
public static Singleton getInstance(){
return INSTANCE;
}
public static void main(String[] args) {
for (int i=0;i<10;i++)
new Thread(()->{
System.out.println(Singleton.getInstance().hashCode());
}).start();
}
}
运行结果显示都是同一个对象
============================================================================================================
2.懒汉式的三种写法1.枚举写法(最完美的写法推荐)
@SpringBootTest
public enum Singleton4 {//枚举类型创建单列
INSTANCE;
public static void main(String[] args) {
for(int i=0;i<10;i++){
new Thread(()->{
System.out.println(Singleton4.INSTANCE.hashCode());
}).start();
}
}
}
===========================================================================================================
2.静态内部类写法/**
* @author: Lei
* @Description:
* @date: 2022/5/13
* JVM保证线程安全
**/
@SpringBootTest
public class Singleton3 {//静态内部类方式
private static Singleton3 INSTANCE;
private static class mySingleton{
private static final Singleton3 INSTANCE=new Singleton3();
}
public Singleton3 getINSTANCE(){
return mySingleton.INSTANCE;
}
public static void main(String[] args) {
for (int i=0;i<10;i++)
new Thread(()->{
System.out.println(Singleton.getInstance().hashCode());
}).start();
}
}
============================================================================================================
双重检测锁写法这种方式只能用synchronize保证线程安全所以需要双重判断
/**
* @author: Lei
* @Description:
* @date: 2022/5/13
**/
@SpringBootTest
public class Singleton2 {//懒汉式
private static Singleton2 INSTANCE;
private Singleton2(){};
public static Singleton2 getInstance(){
if(INSTANCE==null){//双重检测锁实现线程安全
synchronized (Singleton2.class){
if (INSTANCE==null){
INSTANCE=new Singleton2();
}
}
}
return INSTANCE;
}
public static void main(String[] args) {
for (int i=0;i<10;i++)
new Thread(()->{
System.out.println(Singleton.getInstance().hashCode());
}).start();
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)