1、懒汉模式一
package com.hao.demo.design.singel;
/**
* @author haoxiansheng
* @date 2020-05-13
*/
public class SingletonTest3 {
public static void main(String[] args) {
Singleton3 instance2 = Singleton3.getInstance();
Singleton3 instance1 = Singleton3.getInstance();
System.out.println("instance1 => " + instance1.hashCode());
System.out.println("instance2 => " + instance2.hashCode());
}
}
// 懒汉式一 线程不安全
/**
*分析:
* 1、起到了Lazy Loading效果
* 2、单线程条件下可以使用,多线程情况下会产生多个实例 线程不安全
* 3、实际开发中不能用
*/
class Singleton3{
private static Singleton3 singleton;
// 1、构造器私有
private Singleton3() {
}
/**
* 提供静态的公有方法,当使用到该方法时,才去创建 =》懒汉式
*/
public static Singleton3 getInstance() {
if (singleton == null) {
singleton = new Singleton3();
}
return singleton;
}
}
2、懒汉模式二
package com.hao.demo.design.singel;
/**
* @author haoxiansheng
* @date 2020-05-13
*/
public class SingletonTest4 {
public static void main(String[] args) {
Singleton4 instance2 = Singleton4.getInstance();
Singleton4 instance1 = Singleton4.getInstance();
System.out.println("instance1 => " + instance1.hashCode());
System.out.println("instance2 => " + instance2.hashCode());
}
}
// 懒汉式二 同步方法
/**
*分析:
* 1、起到了Lazy Loading效果
* 2、解决了线程安全问题 synchronized
* 3、效率比较低 实例只是第一次才需要同步后面都不需要,单加了synchronized多线程每次获取都要
* 在getInstance() 变成有序的执行
* 4、实际生产中不推荐使用
*/
class Singleton4{
private static Singleton4 singleton;
// 1、构造器私有
private Singleton4() {
}
/**
* 提供静态的公有方法,当使用到该方法时,才去创建 =》懒汉式 加入了同步synchronized
*/
public static synchronized Singleton4 getInstance() { // 线程同步
if (singleton == null) {
singleton = new Singleton4();
}
return singleton;
}
}
3、懒汉模式三 双重检查机制
package com.hao.demo.design.singel;
/**
* @author haoxiansheng
* @date 2020-05-13
*/
public class SingletonTest6 {
public static void main(String[] args) {
Singleton6 instance1 = Singleton6.getInstance();
Singleton6 instance2 = Singleton6.getInstance();
System.out.println("instance1 => " + instance1.hashCode());
System.out.println("instance2 => " + instance2.hashCode());
}
}
// 懒汉式三 双重检查机制 volatile + synchronized 两次判断
/**
*分析:
* 1、起到了Lazy Loading效果
* 2、解决了线程安全问题 volatile 保证可见性
* 3、synchronized 同步
* 4、实际生产中推荐使用
*/
class Singleton6{
private volatile static Singleton6 singleton; //
// 1、构造器私有
private Singleton6() {
}
/**
* 提供静态的公有方法,当使用到该方法时,才去创建 =》懒汉式 加入了同步synchronized
*/
public static Singleton6 getInstance() { // 线程同步
if (singleton == null) {
synchronized(Singleton6.class) {
if (singleton == null) {
singleton = new Singleton6();
}
}
}
return singleton;
}
}