package singleton;
public class Singleton1 {
//私有化构造方法
private Singleton1() {
System.out.println("this is a singleton pattern");
}
//通过自身创建一个实例对象
private static Singleton1 instance = new Singleton1();
//获取此对象的方法
public static Singleton1 getinstance() {
return instance;
}
}
懒汉式:会造成多线程不安全的问题
package singleton;
//懒汉式
public class Singleton2 {
private static Singleton2 instance;
private Singleton2() {
}
;
public static Singleton2 getInstance() {
if (instance == null) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
instance = new Singleton2();
}
return instance;
}
}
package singleton;
public class Main {
public static void main(String[] args) {
for (int i=0;i<100;i++){
new Thread(()->
System.out.println(Singleton2.getInstance().hashCode())
).start();
}
}
}
双重检查
package singleton;
//双重检查
public class Singleton3 {
private static Singleton3 instance;
private Singleton3() {
}
;
public static Singleton3 getInstance() {
//判断是否为空
if (instance == null) {
synchronized (Singleton3.class) {
if (instance == null) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
instance = new Singleton3();
}
}
}
return instance;
}
}
package singleton;
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
new Thread(() -> System.out.println(Singleton3.getInstance().hashCode())).start();
}
}
}
另外一种方式:
package singleton;
public class Singleton4 {
private Singleton4(){};
private static class instanceGet{
private static final Singleton4 instance = new Singleton4();
}
public static Singleton4 getInstance(){
return instanceGet.instance;
}
}
最后的枚举单例:
枚举没有构造方法
package singleton;
public enum Singleton5 {
INSTANCE;
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
new Thread(() -> System.out.println(Singleton5.INSTANCE.hashCode())).start();
}
}
}