設計模式之懶漢單例非線程安全

package design.singletonLazy.demo;

public class Main {

    public static void main(String[] args) {
        // 創建多線程驗證
        Thread t1 = new Thread() {
            @Override
            public void run() {
                SingletonLazyUnsafetyEntity s = SingletonLazyUnsafetyEntity.getSingletonEntity();
                System.out.println("t1線程獲取對象的hashcode: " + s.hashCode());
            }
        };
        Thread t2 = new Thread() {
            @Override
            public void run() {
                SingletonLazyUnsafetyEntity s = SingletonLazyUnsafetyEntity.getSingletonEntity();
                System.out.println("t2線程獲取對象的hashcode: " + s.hashCode());
            }
        };
        Thread t3 = new Thread() {
            @Override
            public void run() {
                SingletonLazyUnsafetyEntity s = SingletonLazyUnsafetyEntity.getSingletonEntity();
                System.out.println("t3線程獲取對象的hashcode: " + s.hashCode());
            }
        };
        t1.start();
        t2.start();
        t3.start();
    }

}
//如果相同則多啓動幾次試試
// t1線程獲取對象的hashcode: 475341210
// t2線程獲取對象的hashcode: 162086129
// t3線程獲取對象的hashcode: 162086129
package design.singletonLazy.demo;

//懶漢式單例-非線程安全
public class SingletonLazyUnsafetyEntity {

    // 直接創建對象實例
    private static SingletonLazyUnsafetyEntity s = null;

    // 實例輸出出口
    public static SingletonLazyUnsafetyEntity getSingletonEntity() {
        if (s == null) {
            s = new SingletonLazyUnsafetyEntity();
        }
        return s;
    }

    // 私有化構造方法,讓外部無法通過new創建
    private SingletonLazyUnsafetyEntity() {

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