使用volatile的特性(保证可见性),实现单例模式
package com.dada.thread.threaddemo.chapter03;
/**
* @author: dada
* @date: 2020/12/17
* @description: 单例模式
*/
public class SingleDemo {
private static volatile SingleDemo instance = null;
private SingleDemo(){
System.out.println(Thread.currentThread().getName() + "\t 单例");
}
public static SingleDemo getInstance(){
if (instance == null) {
synchronized (SingleDemo.class){
if (instance == null){
instance = new SingleDemo();
}
}
}
return instance;
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
new Thread(() ->{
System.out.println(SingleDemo.getInstance() == SingleDemo.getInstance());
} ).start();
}
}
}
输出:
Thread-0 单例
true
true
true
true
true
true
true
true
true
true
Process finished with exit code 0
博客介绍了利用volatile保证可见性的特性来实现单例模式,涉及到多线程环境下单例模式的实现方法,体现了设计模式在实际编程中的应用。
3445

被折叠的 条评论
为什么被折叠?



