Author:老九
计算机专业
可控之事 沉重冷静 不可控之事 乐观面对
[email protected]
☺️
❓ ❤️ ☕️ ❗️
————————————————
版权声明:本文为CSDN博主「浦上青天」的原创文章
//饿汉模式 饿汉模式就是在类加载的时候就将唯一的实例创建好,线程安全,但是效率低
class HungrySingle{
private HungrySingle(){}
private static HungrySingle single = new HungrySingle();
public static HungrySingle getSingle(){
return single;
}
}
public class ThreadTest {
public static void main(String[] args) {
HungrySingle single = HungrySingle.getSingle();
HungrySingle single1 = HungrySingle.getSingle();
System.out.println(single == single1);
}
}
//懒汉模式 懒汉模式是在用到该实例的时候采取创建一个实例,后面如果再创建实例只是返回原有实例,线程不安全
class LazySingle {
private LazySingle() {
}
private static LazySingle single;
public static LazySingle getSingle() {
if (single == null) {
single = new LazySingle();
}
return single;
}
}
public class ThreadTest {
public static void main(String[] args) {
LazySingle single = LazySingle.getSingle();
LazySingle single1 = LazySingle.getSingle();
System.out.println(single == single1);
}
}
//懒汉模式 懒汉模式是在用到该实例的时候采取创建一个实例,后面如果再创建实例只是返回原有实例,线程不安全
class LazySingle {
private LazySingle() {
}
private static LazySingle single;
public synchronized static LazySingle getSingle() {
if (single == null) {
single = new LazySingle();
}
return single;
}
}
public class ThreadTest {
public static void main(String[] args) {
LazySingle single = LazySingle.getSingle();
LazySingle single1 = LazySingle.getSingle();
System.out.println(single == single1);
}
}
//懒汉模式 懒汉模式是在用到该实例的时候采取创建一个实例,后面如果再创建实例只是返回原有实例,线程不安全
class LazySingle {
private LazySingle() {
}
private static LazySingle single;
public static LazySingle getSingle() {
synchronized (LazySingle.class) {
if (single == null) {
single = new LazySingle();
}
}
return single;
}
}
public class ThreadTest {
public static void main(String[] args) {
LazySingle single = LazySingle.getSingle();
LazySingle single1 = LazySingle.getSingle();
System.out.println(single == single1);
}
}
//懒汉模式 懒汉模式是在用到该实例的时候采取创建一个实例,后面如果再创建实例只是返回原有实例,线程不安全
class LazySingle {
private LazySingle() {
}
private static LazySingle single;
public static LazySingle getSingle() {
if(single == null){
synchronized (LazySingle.class) {
if (single == null) {
single = new LazySingle();
}
}
}
return single;
}
}
public class ThreadTest {
public static void main(String[] args) {
LazySingle single = LazySingle.getSingle();
LazySingle single1 = LazySingle.getSingle();
System.out.println(single == single1);
}
}
//懒汉模式 懒汉模式是在用到该实例的时候采取创建一个实例,后面如果再创建实例只是返回原有实例,线程不安全
class LazySingle {
private LazySingle() {
}
private volatile static LazySingle single = null;
public static LazySingle getSingle() {
if(single == null){
synchronized (LazySingle.class) {
if (single == null) {
single = new LazySingle();
}
}
}
return single;
}
}
public class ThreadTest {
public static void main(String[] args) {
LazySingle single = LazySingle.getSingle();
LazySingle single1 = LazySingle.getSingle();
System.out.println(single == single1);
}
先赞后看,养成习惯!!!^ _ ^♥♥♥
每天都更新知识点哦!!!
码字不易,大家的支持就是我坚持下去的动力。点赞后不要忘记关注我哦!