單例模式如何在多執行緒下保證單例

2022-07-01 01:30:08 字數 2767 閱讀 7692

單例模式的實現方式:

1、 使用餓漢模式載入或使用static**塊

public

class

singletonhungry

private

singletonhungry()

public

static

singletonhungry getinstance()

public

static

void

main(string args) }}

執行結果:

2、 使用dcl雙檢查鎖機制(因最近在學習多執行緒技術,所以分別用synchronized和reentrantreadwritelock加鎖做了測試)

a)、使用synchronized加鎖

public

class

singletonbydclsync

public

static

singletonbydclsync getinstance() //}

//}//} catch (interruptedexception e)

syncinit();

return

instance;

}//同步的靜態方法與類鎖效果一樣

synchronized

private

static

void

syncinit()

//為了與reentrantreadwritelock效率做對比

thread.sleep(2000);

} catch

(interruptedexception e)

}public

static

void

main(string args) }}

執行結果:

b)、使用reentrantreadwritelock加鎖

public

class

singletonbydcllock

public

static

singletonbydcllock getinstance()

} catch

(interruptedexception e)

finally

}return

instance;

}public

static

void

main(string args) }}

執行結果:

從執行結果證明了reentrantreadwritelock讀鎖共享原理,大家也可以嘗試一下寫鎖、 「讀寫鎖」、「寫讀鎖」的效果,這些的效果跟synchronized是一樣的,因為它們都是互斥(同步)。

3、 使用靜態內建類(推薦)

public

class singletonbyinner implements

serializable

private

singletonbyinner()

public

static

singletonbyinner getinstance()

//protected object readresolve()

public

static

void

main(string args)

catch

(ioexception e)

//反序列化

try

catch

(classnotfoundexception e)

catch

(ioexception e)

}).start();}}

}

不呼叫readresolve()方法的情況下,執行結果:

將注釋**解開,呼叫readresolve()方法,執行結果:

注:之所以要呼叫readresolve()方法,是因為此類實現了序列化介面,進行了序列化操作,破壞了單例模式。其它實現方式如果進行了序列化操作,同樣需要呼叫readresolve()方法。

4、 使用enum列舉資料型別(列舉enum和靜態**塊的特性相似,構造方法會自動被呼叫)

public

class

singletonbyenum

public

object getobj()

}private

singletonbyenum()

public

static

object getinstance()

public

static

void

main(string args) }}

執行結果:

多執行緒 單例模式

單例模式 是非常典型常用的一種設計模式 乙份資源只能被申 載一次 單例模式的方法建立的類在當前程序中只有乙個例項 資源的程式初始化的時候就去載入,後面使用的時候直接使用,使用的時候比較流暢,有可能會載入用不上的資源,導致程式初始化時間比較慢。include class single instance...

單例模式多執行緒

單例模式 確保某個類只有乙個例項化物件 import time class a from threading import lock instance none lock lock def new cls,args,kwargs 加鎖確保時間片不發生輪轉 with cls.lock ifnot cl...

多執行緒下的單例模式

單例模式分為兩種 懶漢單例模式和餓漢式單例模式 public class singleton private static singleton single null public static singleton getinstance return single 在單執行緒中,這樣寫,不會存在任...