package com.java3y.austin.test.Mode;
import java.util.HashSet;
import java.util.concurrent.atomic.AtomicBoolean;
// 饿汉式单例
class Singleton1 {
private Singleton1() {
}
private static final Singleton1 singleton1 = new Singleton1();
public static Singleton1 getSingleton() {
return singleton1;
}
public static void test() {
Singleton1 singleton11 = Singleton1.getSingleton();
AtomicBoolean isSingleton = new AtomicBoolean(true);
System.out.println("==========Singleton1==============");
for (int i = 0; i < 10; i++) {
new Thread(() -> {
Singleton1 singleton12 = Singleton1.getSingleton();
if (singleton11 != singleton12 && !singleton11.equals(singleton12)) {
isSingleton.set(false);
}
}).start();
}
System.out.println(isSingleton.get() == true ? "Singleton" : "No Singleton");
}
}
// DCL,双重检测机制
class Singleton2 {
private Singleton2() {
}
// 防止指令重排序,创建对象不是原子性的
private static volatile Singleton2 singleton2 = null;
public static Singleton2 getSingleton2() {
if (singleton2 == null) { // 避免多次获取锁
synchronized (Singleton2.class) {
if (singleton2 == null) {
singleton2 = new Singleton2();
}
}
}
return singleton2;
}
public void test() {
HashSet<Singleton2> hashSet = new HashSet<>(100);
System.out.println("==========Singleton2==============");
for (int i = 0; i < 1000; i++) {
new Thread(() -> {
Singleton2 singleton12 = Singleton2.getSingleton2();
hashSet.add(singleton12);
}).start();
}
System.out.println(hashSet.size());
}
}
/**
* 静态内部类实现单例模式
* 静态内部类只有在被调用时才会加载,且只加载一次, 实现懒加载效果和线程安全
* 类加载器在加载类时会使用一种叫做"类加载锁"的机制,保证在同一时间只有一个线程能够加载该类
*/
class Singleton3 {
private Singleton3() {
}
private static class SingletonInner {
private static final Singleton3 singleton = new Singleton3();
}
public static Singleton3 getInstance3() {
return SingletonInner.singleton;
}
public static void test() {
Singleton3 singleton11 = Singleton3.getInstance3();
AtomicBoolean isSingleton = new AtomicBoolean(true);
System.out.println("==========Singleton3==============");
for (int i = 0; i < 10; i++) {
new Thread(() -> {
Singleton3 singleton12 = Singleton3.getInstance3();
if (singleton11 != singleton12 && !singleton11.equals(singleton12)) {
isSingleton.set(false);
}
}).start();
}
System.out.println(isSingleton.get() == true ? "Singleton" : "No Singleton");
}
}
public class SingletonTest {
public static void main(String[] args) {
// 写的test方法无法验证是否单例
}
}
标签:Java,模式,static,单例,Singleton2,Singleton3,new,Singleton1,public
From: https://www.cnblogs.com/jishaling/p/17678341.html