設計模式之單例模式

2021-10-01 04:30:54 字數 2068 閱讀 4713

單例模式一共分為兩種 餓漢模式和懶漢模式

public class student1 

// 3:對外提供公共方法獲取物件

public static student1 getsingletoninstance()

}

1.執行緒安全

public class student5 

/* * 此處使用乙個內部類來維護單例 jvm在類載入的時候,是互斥的,所以可以由此保證執行緒安全

問題 */

private static class singletonfactory

/* 獲取例項 */

public static student5 getsingletoninstance()

}

1執行緒不安全

public class student2 

//2:定義私有靜態成員變數,先不初始化

private static student2 student = null;

//3:定義公開靜態方法,獲取本身物件

public static student2 getsingletoninstance()

//有物件就返回已有物件

return student;

}

2.執行緒安全但鎖加的太大了,效能不行

public class student3 

private static student3 student = null;

// 此處考驗對synchronized知識點的掌握情況

public static synchronized student3 getsingletoninstance()

return student; }

}

3.因為jit有指令重排序,可能會出現問題,

public class student4 

// 此處考驗對synchronized知識點的掌握情況

public static student4 getsingletoninstance()

}} return student;

}

4.懶漢模式的雙重檢查鎖,真正安全

public class student5 

public static student5 getsingletoninstance()

}} return student;// 後面b執行緒執行時將引發:物件尚未初始化錯誤。

}}

jvm中的物件建立過程是什麼流程?

student student = new student();// 高階語言

a)new關鍵字會觸發student類的類載入(如果已載入,則此步驟作廢)

b)根據class物件中的資訊,去開闢相應大小的記憶體空間。

c)初始化student物件,就是完成成員變數的初始化操作(到這一步,我們才能說該物件是可用的)

d)將開闢出來的記憶體空間位址,賦值給棧空間的變數student

以上步驟,其實都是通過位元組碼指令去完成的。

物理機器直接操作的都是cpu指令(原子性其實是相對我們cpu指令來說的)

有序性

int x = 10;

boolean flag = false;

x ++;

flag = true;

如果兩行**的執行順序交換之後,不會影響最終的程式執行結果,那麼jit即時編譯器會根據情況去進行指令重排序。

乙個是禁止指令重排序。

另乙個作用是禁止使用cpu快取。

可見性
在cpu單核時代,執行緒1和執行緒2使用的是同乙個cpu快取,所以執行緒之間的資料是可見的。

在cpu多核時代,執行緒1在a核,執行緒2在b核,每個核都有自己的cpu快取空間,

如果執行緒1產生的資料快取沒有同步到執行緒2對應的cpu快取,則會出現可見性問題。

設計模式之單例模式

前一段時間買了一本秦小波寫的 設計模式之禪 網上對這書的評價很高。現在還沒有看很多,但是有些地方頗有感觸,也並不是所有的地方都能看懂,但是會慢慢研究的。自己對於設計模式的感覺就是乙個字 牛!感覺會23種設計模式並且會熟練運用的人,真的就是大師級的牛人了,設計模式是乙個專案主管或者架構師一定要會的東西...

設計模式之單例模式

package com.xie.singleton public class singleton 提供乙個共有的靜態的入口方法 public static singleton getinstance 懶漢式 延遲載入 提供乙個私有的靜態的成員變數,但不做初始化 private static sing...

設計模式之 單例模式

單例模式 singleton 保證乙個類僅有乙個例項,並提供乙個訪問它的全域性訪問點。單例模式 單件模式 使用方法返回唯一的例項 public class singleton private static singleton instance public static singleton geti...