系列文章目录
单例模式之懒汉式(线程安全,同步方法)
单例模式之懒汉式(线程安全,同步代码块)
单例模式之DoubleCheck
文章目录
前言
Hello,小伙伴们,欢迎来到柚子的博客~让我们一起成长吧o( ̄▽ ̄)ブ
提示:以下是本篇文章正文内容,下面案例可供参考
一、单例—线程安全,同步方法懒汉式
1.懒汉式(线程安全,同步方法)案例
代码如下(示例):
public class SingletonTest04 {
public static void main(String[] args) {
System.out.println("懒汉式2,线程安全~");
Singleton instance = Singleton.getInstance();
Singleton instance2 = Singleton.getInstance();
System.out.println(instance == instance2);//true
System.out.println("instance.hashCode=" + instance.hashCode());
System.out.println("instance.hashCode=" + instance2.hashCode());
}
}
//懒汉式(线程安全,同步方法)
class Singleton {
private static Singleton instance;
private Singleton() {}
//提供一个静态的公有方法,加入同步处理的代码,解决线程安全问题
//即懒汉式
public static synchronized Singleton getInstance() {
if(instance == null) {
instance = new Singleton();
}
return instance;
}
}
2.懒汉式(线程安全,同步方法)优缺点
(1)解决了线程不安全问题。
(2)效率太低了,每个线程在想获得类的实例时候,执行getInstance()方法都要进行同步。而其实这个方法只执行一次实例化代码就够了,后面的想获得该类实例,直接return就行了。方法进行同步效率太低。
(3)结论:在实际开发中,不推荐使用这种方式。
二、单例—线程安全,同步代码块懒汉式
1.懒汉式(线程安全,同步代码块)案例
代码如下(示例):
class Singleton {
private static Singleton singleton;
private Singleton() {}
public static Singleton getInstance() {
if (singleton == null) {
synchronized (Singleton.class) {
singleton = new Singleton();
}
}
}
}
2.懒汉式(线程安全,同步代码块)优缺点
(1)这种方式,本意是想对懒汉式(线程安全,同步代码块)实现方式的改进,因为前面同步方法效率太低,改为同步产生实例化的代码块。
(2)但是这种同步并不能起到线程同步的作用。跟线程不安全懒汉式遇到的情形一致,假如一个线程进入了if(singleton == null)判断语句块,还未来得及往下执行,另一个线程也通过了这个判断语句,这时便会产生多个实例。
(3)结论:在实际开发中,不能使用这种方式。
三、单例—DoubleCheck
1.DoubleCheck案例
代码如下(示例):
public class SingletonTest06 {
public static void main(String[] args) {
System.out.println("数据检查");
Singleton instance = Singleton.getInstance();
Singleton instance2 = Singleton.getInstance();
System.out.println(instance == instance2);//true
System.out.println("instance.hashCode=" + instance.hashCode());
System.out.println("instance.hashCode=" + instance2.hashCode());
}
}
class Singleton {
private static volatile Singleton instance;
private Singleton() {}
//提供一个静态的公有方法,加入双重检查代码,解决线程安全问题,同时解决懒加载问题
//同时保证了效率,推荐使用
public static Singleton getInstance() {
if(instance == null){
synchronized (Singleton.class) {
if(instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
2.DoubleCheck优缺点
(1)Double-Check概念是多线程开发中常使用到的,如代码中所示,我们进行了两次if(singleton == null)检查,这样就可以保证线程安全了。
(2)这样,实例化代码只用执行一次,后面再次访问时,判断if(singleton等于null),直接return实例化对象,也避免反复进行方法同步。
(3)线程安全;延迟加载;效率较高。
(4)结论:在实际开发中,推荐使用这种单例设计模式。
总结
单例模式之懒汉式(线程安全,同步方法)——不推荐使用
单例模式之懒汉式(线程安全,同步代码块)——不能使用
单例模式之DoubleCheck——推荐使用
╭◜◝ ͡ ◜◝╮
( ˃̶͈◡˂ ̶͈ )感觉有用的话,欢迎点赞评论呀!
╰◟◞ ͜ ◟◞╯