【原创声明】此文为本人原创,欢迎转载,转载请注明出处,作者链接~
http://www.cnblogs.com/m-yb/p/8833085.html
单例很常用,面试也经常被问,如:不用自定义锁怎么实现线程安全的单例?
下面我将分别介绍饿汉、懒汉的单例(都是线程安全的):
饿汉单例:
package com.dayuanit.utils.hungry; public class Singleton {
private static final Singleton instance = new Singleton();
private Singleton(){}
public static Singleton getInstance(){
return instance;
}
}
懒汉单例:
package com.dayuanit.utils.lazy; public class Singleton {
private static volatile Singleton instance;
private Singleton(){}
public static Singleton getInstance(){
if (null == instance){
synchronized (Singleton.class){
if (null == instance){
instance = new Singleton();
}
}
}
return instance;
}
}
懒汉(静态内部类方式):
//静态内部类方式
public class Bird { private Bird(){ } public static Bird getBird(){
return BirdInstance.bird;
} private static class BirdInstance{
public static final Bird bird = new Bird();
}
}
懒汉(枚举方式):
//枚举方式
public enum Person { instance; public static Person getPerson(){
return instance;
} }
推荐枚举方式,静态内部类方式也可。
上述单例可以用如下方式检验是否为单例,true则为单例:
package com.dayuanit.utils.hungry; public class Test {
public static void main(String[] args) {
Singleton singleton1 = Singleton.getInstance();
Singleton singleton2 = Singleton.getInstance(); System.out.println(singleton1 == singleton2); }
}
完毕,各位看官觉得很赞的,留言评论,点赞~
本人才疏学浅,有疑问有误的地方,欢迎讨论~
没有英汉互译结果
请尝试网页搜索
请尝试网页搜索