注释的部分是普通的懒汉式,改成通过静态内部类的懒汉方式
/**
* 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
…