使用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