package com.chendan.mianshi;
/**
*
*
* @Description
* @author ChenDan 624665255@qq.com
* @date 2019年8月4日下午8:47:13
*
*/
public class MianShiTest2 {
public static void main(String[] args) {
// com.chendan.mianshi.SingleTon@1c53fd30
// com.chendan.mianshi.SingleTon@1c53fd30
// 可以看到结果一样
getInstanceEhs();
// com.chendan.mianshi.SingleTon2@282ba1e
// com.chendan.mianshi.SingleTon2@282ba1e
getInstanceLhs();
//com.chendan.mianshi.SingleTon3@f5f2bb7
//com.chendan.mianshi.SingleTon3@f5f2bb7
getInstanceLhs2();
}
// 饿汉式方法
public static void getInstanceEhs() {
// 调用GetInstance直接返回一个instance对象,且是唯一的
SingleTon instance1 = SingleTon.getInstance();
SingleTon instance2 = SingleTon.getInstance();
// com.chendan.mianshi.SingleTon@1c53fd30
System.out.println(instance1);
// com.chendan.mianshi.SingleTon@1c53fd30
System.out.println(instance2);
}
// 懒汉式方法
public static void getInstanceLhs() {
// 调用getInstance直接返回一个instance对象,且是唯一的
SingleTon2 instance1 = SingleTon2.getInstance();
SingleTon2 instance2 = SingleTon2.getInstance();
// ccom.chendan.mianshi.SingleTon2@cad498c
System.out.println(instance1);
// com.chendan.mianshi.SingleTon2@cad498c
System.out.println(instance2);
}
public static void getInstanceLhs2() {
// 调用getInstance直接返回一个instance对象,且是唯一的
SingleTon3 instance1 = SingleTon3.getInstance();
SingleTon3 instance2 = SingleTon3.getInstance();
// com.chendan.mianshi.SingleTon2@cad498c
System.out.println(instance1);
// com.chendan.mianshi.SingleTon2@cad498c
System.out.println(instance2);
}
}
//饿汉式直接初始化方法
class SingleTon {
private SingleTon() {
}
// 饿汉式直接静态初始化,保证唯一,但是初始类时就加载内存,性能稍低
private static SingleTon instance = new SingleTon();
// 创建直接返回线程方法
public static SingleTon getInstance() {
return instance;
}
}
//懒汉式静态内部类初始化方法
class SingleTon2 {
private SingleTon2() {
}
private static class Singleton2Holder {
public final static SingleTon2 instance = new SingleTon2();
}
public static SingleTon2 getInstance() {
return Singleton2Holder.instance;
}
}
class SingleTon3 {
private SingleTon3() {
}
public static SingleTon3 instance = null;
public static SingleTon3 getInstance() {
if (instance == null) {
synchronized (SingleTon3.class) {
if (instance == null) {
instance = new SingleTon3();
}
}
}
return instance;
}
}
总结:最优方法为内部静态类的方法,即方法2
原文:https://blog.51cto.com/9447803/2426526