1.饿汉式(静态参数)
class Student {
private static Student instance
= new Student();
private Student
(){}
public static Student
getInstance() {
return instance
;
}
}
2.饿汉式(静态代码块)
class Student {
private static Student instance
= null
;
static {
instance
= new Student();
}
private Student
(){}
public static Student
getInstance() {
return instance
;
}
}
3.懒汉式(线程不安全)
class Student {
private static Student instance
;
private Student
(){}
public static Student
getInstance() {
if (instance
== null
) {
instance
= new Student();
}
return instance
;
}
}
4.懒汉式(线程安全)
class Student {
private static Student instance
;
private Student
(){}
public static synchronized Student
getInstance() {
if (instance
== null
) {
instance
= new Student();
}
return instance
;
}
}
5.静态内部类
class Student {
private static class StudentHolder {
private static final Student INSTANCE
= new Student();
}
private Student
(){}
public static final Student
getInstance() {
return StudentHolder
.INSTANCE
;
}
}
6.枚举
enum Student
{
INSTANCE
;
}
7.双重校验锁
class Student {
private volatile static Student stu
;
private Student
(){}
public static Student
getInstance() {
if (stu
== null
) {
synchronized (Student
.class) {
if (stu
== null
) {
stu
= new Student();
}
}
}
return stu
;
}
}
转载请注明原文地址:https://tech.qufami.com/read-12879.html