第一种:
- public class Singleton2 {
- private Singleton2(){
- System.out.println("This is Singleton2's instance.");
- };
- private static Singleton2 instance = null;
- public static Singleton2 getInstance(){
- if(instance == null) {
- instance = new Singleton2();
- }
- return instance;
- }
- }
这种情况未加锁,可能会产生数据错误,比如两个同时新生成的对象,一个把对象数据改变了,而另一个使用的没改变之前的
第二种:
- public class Singleton1 {
- private Singleton1(){
- System.out.println("This is Singleton1's instance.");
- }
- private static Singleton1 instance = null;
- public static Singleton1 getInstance2() {
- if(instance == null){ //1
- synchronized (Singleton1.class) { //2
- if(instance == null) {
- instance = new Singleton1();
- }
- }
- }
- return instance;
- }
- }
这种只会在第一次的时候产生阻塞,之后每实例一次对象,就会在第1步时跳过去,在第一次实例的时候,会在第2步那里产生阻塞,以后就不会了,这种相对来说是最好的
第三种:
- public class Singleton1 {
- private Singleton1(){
- System.out.println("This is Singleton1's instance.");
- }
- private static Singleton1 instance = null;
- public static synchronized Singleton1 getInstance(){ //1
- if(instance == null){
- instance = new Singleton1();
- }
- return instance;
- }
- }
多线程的时候每次都会在1这里产生阻塞。
附上原帖地址:http://blog.csdn.net/withiter/article/details/8140338
本文详细解析了Java单例模式的三种常见实现方法,并对比了它们的优缺点,包括线程安全和效率方面的考量。通过实例代码演示,帮助开发者理解如何在不同场景下选择合适的单例模式实现。

1321

被折叠的 条评论
为什么被折叠?



