设计模式之饿汉单例

时间:2021-02-22 20:47:37
package design.singleton.demo;

//饿汉式单例
public class SingletonHungryEntity {

//直接创建对象实例
private static SingletonHungryEntity s = new SingletonHungryEntity();

// 实例输出出口
public static SingletonHungryEntity getSingletonEntity() {
return s;
}

// 私有化构造方法,让外部无法通过new创建
private SingletonHungryEntity() {

}
}
package design.singleton.demo;

public class Main {

public static void main(String[] args) {
// 创建多线程验证
Thread t1 = new Thread() {
@Override
public void run() {
SingletonHungryEntity s = SingletonHungryEntity.getSingletonEntity();
System.out.println("t1线程获取对象的hashcode: " + s.hashCode());
}
};
Thread t2 = new Thread() {
@Override
public void run() {
SingletonHungryEntity s = SingletonHungryEntity.getSingletonEntity();
System.out.println("t2线程获取对象的hashcode: " + s.hashCode());
}
};
Thread t3 = new Thread() {
@Override
public void run() {
SingletonHungryEntity s = SingletonHungryEntity.getSingletonEntity();
System.out.println("t3线程获取对象的hashcode: " + s.hashCode());
}
};
t1.start();
t2.start();
t3.start();
}

}
// t3线程获取对象的hashcode: 475341210
// t1线程获取对象的hashcode: 475341210
// t2线程获取对象的hashcode: 475341210