简单单例模式

懒汉、饿汉

// 懒汉式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class Apple {

private static Apple apple = null;

private Apple(){}

//synchronized使用来对方法进行线程同步的,即一定时间内只能有一个线程调用该方法
public static synchronized Apple getApple(){
if(apple == null) {
apple = new Apple(); //需要时再创建Apple实例,需要加synchronized,防止并发操作时多个线程同时创建多个实例
}
return apple;
}
}

// 饿汉式

1
2
3
4
5
6
7
8
9
10
public class Apple {

private static Apple apple = new Apple(); //提前创建Apple实例

private Apple(){}

public static Apple getApple(){ //不需要加synchronized,也能应对并发操作
return apple;
}
}

另:Java单例模式中双重检查锁的问题

---------------- The End ----------------
0%