设计模式-单例模式
说明
单例模式一共有 8 种, 但是只有 5 种是线程安全的
- 饿汉式
- 懒汉式-直接加锁
- 懒汉式-双重检锁(性能好)
- 静态内部类
- 枚举
饿汉式
package com.shaoming.patterns.singleton;
/**
* 饿汉式
* 简单实用 , 线程安全
* 推荐使用!!! 工作中可以使用
* 唯一缺点 : 不使用该类示例也会进行实例化
*/
public class Singleton01 {
private static final Singleton01 INSTANCE = new Singleton01();
// 私有化构造器
private Singleton01(){}
public static Singleton01 getInstance(){
return INSTANCE;
}
public void sayHello(){
System.out.println("hello singleton01");
}
public static void main(String[] args) {
// 第一种方式
Singleton01 instance011 = Singleton01.getInstance();
Singleton01 instance012 = Singleton01.getInstance();
System.out.println(instance011==instance012);
}
}
懒汉式-直接加锁
package com.shaoming.patterns.singleton;
/**
懒汉式
存在线程安全问题 , 需要加 synchronized
缺点: 性能有问题
这种方式用的少
*/
public class Singleton02 {
private static Singleton02 INSTANCE;
private Singleton02(){}
public static synchronized Singleton02 getInstance(){
if(INSTANCE==null){
try {
Thread.sleep(1);
} catch (Exception e) {
e.printStackTrace();
}
INSTANCE = new Singleton02();
}
return INSTANCE;
}
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
new Thread(()->{
System.out.println(Singleton02.getInstance().hashCode());
}).start();
}
}
}
懒汉式-双重检锁
package com.shaoming.patterns.singleton;
/**
* 饿汉式
* 双重检锁
* 缺点: 代码量复杂
*/
public class Singleton03 {
// 需要加上 volatile
private static volatile Singleton03 INSTANCE;
private Singleton03(){}
public static Singleton03 getInstance(){
if(INSTANCE==null){
synchronized (Singleton03.class){
if(INSTANCE==null){
try {
Thread.sleep(1);
} catch (Exception e) {
e.printStackTrace();
}
INSTANCE = new Singleton03();
}
}
}
return INSTANCE;
}
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
new Thread(()->{
System.out.println(Singleton03.getInstance().hashCode());
}).start();
}
}
}
静态内部类
package com.shaoming.patterns.singleton;
/**
* 静态内部类
* 优点: 代码量少 , 不需要时候不进行实例初始化
* 只加载 singleton04 , 静态内部类不会被下载 , 调用 getInstance() 方法 ,才会加载内部类 , jvm 帮我们保证
*/
public class Singleton04 {
private Singleton04(){}
private static class Singleton04Holder{
private final static Singleton04 INSTANCE = new Singleton04();
}
public static Singleton04 getInstance(){
return Singleton04Holder.INSTANCE;
}
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
new Thread(()->{
System.out.println(Singleton04.getInstance().hashCode());
}).start();
}
}
}
枚举
package com.shaoming.patterns.singleton;
/**
* 枚举
*/
public enum Singleton05 {
INSTANCE;
private void sayHello(){
System.out.println("say hello ==> enum");
}
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
new Thread(()->{
System.out.println(Singleton05.INSTANCE.hashCode());
}).start();
}
}
}
总结
int i = 0; i < 100; i++) {
new Thread(()->{
System.out.println(Singleton05.INSTANCE.hashCode());
}).start();
}
}
}
# 总结
使用 饿汉式 最简单 , 最好理解,线程安全 ,工作中可以使用