公平鎖與非公平鎖

2021-07-27 02:58:35 字數 1797 閱讀 8133

reentrantlock中很明顯可以看到其中同步包括兩種,分別是公平的fairsync和非公平的nonfairsync。公平鎖的作用就是嚴格按照執行緒啟動的順序來執行的,不允許其他執行緒插隊執行的;而非公平鎖是允許插隊的。

預設情況下reentrantlock是通過非公平鎖來進行同步的,包括synchronized關鍵字都是如此,因為這樣效能會更好。因為從執行緒進入了runnable狀態,可以執行開始,到實際執行緒執行是要比較久的時間的。而且,在乙個鎖釋放之後,其他的執行緒會需要重新來獲取鎖。其中經歷了持有鎖的執行緒釋放鎖,其他執行緒從掛起恢復到runnable狀態,其他執行緒請求鎖,獲得鎖,執行緒執行,這一系列步驟。如果這個時候,存在乙個執行緒直接請求鎖,可能就避開掛起到恢復runnable狀態的這段消耗,所以效能更優化。

/**

* creates an instance of .

* this is equivalent to using .

*/public

reentrantlock()

預設狀態,使用的reentrantlock()就是非公平鎖。再參考如下**,我們知道reentrantlock的獲取鎖的操作是通過裝飾模式**給sync的。

* acquires the lock.

** acquires the lock if

itis

not held by another thread and returns

* immediately, setting the lock hold count

to one.

** if the current thread already holds the lock then

the hold

* count

is incremented by one and

the method returns immediately.

** if the lock is held by another thread then

the * current thread becomes disabled for thread scheduling

* purposes and lies dormant until

the lock has been acquired,

* at which time

the lock hold count

isset

to one.

*/public void lock()

/**

* sync object for non-fair locks

*/static final

class

nonfairsync

extends

sync

}/**

* sync object for fair locks

*/static final

class

fairsync

extends

sync

}

當使用非公平鎖的時候,會立刻嘗試配置狀態,成功了就會插隊執行,失敗了就會和公平鎖的機制一樣,呼叫acquire()方法,以排他的方式來獲取鎖,成功了立刻返回,否則將執行緒加入佇列,知道成功呼叫為止。

公平鎖與非公平鎖

公平鎖與非公平鎖即fairsybc和nonfairsync。簡單說一下兩個鎖的區別 顧名思義,公平就是先到先得,比如a和b執行緒均需要獲得乙個鎖,但是此時鎖正在被另乙個執行緒c佔據著,這是如果a先來b後來。那麼當c釋放鎖以後,a就會獲得這個鎖。如果是非公平的話,可能b後來但是能比a先獲得鎖。reen...

公平鎖與非公平鎖

公平鎖 是指多個執行緒按照申請鎖的順序來獲取鎖,類似排隊打飯,有先來後到。非公平鎖 是指多個執行緒獲取鎖的順序並不是按照申請鎖的順序,有可能後申請的執行緒比先申請的執行緒優先獲取鎖。在高併發的情況下,可能會造成優先順序反轉或者飢餓現象。lock lock newreentrantlock 當使用re...

公平鎖與非公平鎖

看到公平和非公平兩個詞,我們就可以簡單的理解到公平與非公平的含義,公平的意思呢,就是按照排隊順序逐個來進行執行,非公平的含義呢,就是誰更霸道,就更能搶占到執行的優先。所以我們的公平鎖,就是多個執行緒按照執行緒的申請順序,逐個獲得鎖,然後排隊執行。優點 所有的執行緒都能得到資源。缺點 吞吐量會下降很多...