注释的部分是普通的懒汉式,改成通过静态内部类的懒汉方式
/**
* Created by Wangjianxin on 2017/7/7 0007.
*/
public class Singleton{
private static Singleton singleton = null;
private Singleton(){
}
private static class SingletonHolder{
public static Singleton instance = new Singleton();
}
public synchronized static Singleton getIntence(){
return SingletonHolder.instance;
// if(singleton == null){
// return new Singleton();
// }
// return singleton;
}
}
class threads extends Thread{
@Override
public void run() {
System.out.println(Singleton.getIntence().hashCode());
}
public static void main(String[] args) {
for(int i = 0; i< 50;i++){
Thread thread = new threads();
thread.start();
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
输出
79755549
79755549
79755549
79755549
79755549
79755549
79755549
…
本文介绍了一种改进的懒汉式单例模式实现方法,通过静态内部类确保线程安全的同时避免同步带来的性能开销。该实现方式利用了Java类加载机制保证实例创建的唯一性和延迟加载。
2306

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



