設計模式之餓漢單例

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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章