国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 學(xué)院 > 開發(fā)設(shè)計(jì) > 正文

公平鎖與非公平鎖

2019-11-08 03:18:48
字體:
供稿:網(wǎng)友

ReentrantLock中很明顯可以看到其中同步包括兩種,分別是公平的FairSync和非公平的NonfairSync。公平鎖的作用就是嚴(yán)格按照線程啟動(dòng)的順序來執(zhí)行的,不允許其他線程插隊(duì)執(zhí)行的;而非公平鎖是允許插隊(duì)的。

默認(rèn)情況下ReentrantLock是通過非公平鎖來進(jìn)行同步的,包括synchronized關(guān)鍵字都是如此,因?yàn)檫@樣性能會(huì)更好。因?yàn)閺木€程進(jìn)入了RUNNABLE狀態(tài),可以執(zhí)行開始,到實(shí)際線程執(zhí)行是要比較久的時(shí)間的。而且,在一個(gè)鎖釋放之后,其他的線程會(huì)需要重新來獲取鎖。其中經(jīng)歷了持有鎖的線程釋放鎖,其他線程從掛起恢復(fù)到RUNNABLE狀態(tài),其他線程請(qǐng)求鎖,獲得鎖,線程執(zhí)行,這一系列步驟。如果這個(gè)時(shí)候,存在一個(gè)線程直接請(qǐng)求鎖,可能就避開掛起到恢復(fù)RUNNABLE狀態(tài)的這段消耗,所以性能更優(yōu)化。

/** * Creates an instance of {@code ReentrantLock}. * This is equivalent to using {@code ReentrantLock(false)}. */ public ReentrantLock() { sync = new NonfairSync(); }

默認(rèn)狀態(tài),使用的ReentrantLock()就是非公平鎖。再參考如下代碼,我們知道ReentrantLock的獲取鎖的操作是通過裝飾模式代理給sync的。

/** * Acquires the lock. * * <p>Acquires the lock if it is not held by another thread and returns * immediately, setting the lock hold count to one. * * <p>If the current thread already holds the lock then the hold * count is incremented by one and the method returns immediately. * * <p>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 is set to one. */ public void lock() { sync.lock(); }

下面參考一下FairSyncNonfairSync對(duì)lock方法的實(shí)現(xiàn)

/** * Sync object for non-fair locks */ static final class NonfairSync extends Sync { /** * Performs lock. Try immediate barge, backing up to normal * acquire on failure. */ final void lock() { if (compareAndSetState(0, 1)) setExclusiveOwnerThread(Thread.currentThread()); else acquire(1); } } /** * Sync object for fair locks */ static final class FairSync extends Sync { final void lock() { acquire(1); } }

當(dāng)使用非公平鎖的時(shí)候,會(huì)立刻嘗試配置狀態(tài),成功了就會(huì)插隊(duì)執(zhí)行,失敗了就會(huì)和公平鎖的機(jī)制一樣,調(diào)用acquire()方法,以排他的方式來獲取鎖,成功了立刻返回,否則將線程加入隊(duì)列,知道成功調(diào)用為止。


發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 江阴市| 青铜峡市| 孟村| 新津县| 伊川县| 安庆市| 孝义市| 山丹县| 大关县| 无棣县| 龙口市| 龙里县| 班戈县| 星座| 万荣县| 夹江县| 伊宁市| 镇康县| 秀山| 布尔津县| 龙里县| 玉屏| 自治县| 台东县| 桦甸市| 洪泽县| 临清市| 庄浪县| 柞水县| 林州市| 洛川县| 绥棱县| 广元市| 阳谷县| 驻马店市| 江源县| 宜宾市| 安义县| 道真| 石林| 九寨沟县|