模式6--ReadWriteLock
生活随笔
收集整理的這篇文章主要介紹了
模式6--ReadWriteLock
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
來至《java多線程設(shè)計模式》
自己提供一個邏輯鎖代替JDK的物理鎖synchronized
優(yōu)點:1.對read操作不進行共享互斥,可以進行多個read操作,提高系統(tǒng)性能
??????? 2.適合read》write的情況
package Sample;public final class ReadWriteLock {private int readingReaders = 0; // (A)...實際正在讀取的執(zhí)行緒數(shù)量private int waitingWriters = 0; // (B)...正在等待寫入的執(zhí)行緒數(shù)量private int writingWriters = 0; // (C)...實際正在寫入的執(zhí)行緒數(shù)量private boolean preferWriter = true; // 寫入優(yōu)先的話,值為truepublic synchronized void readLock() throws InterruptedException {while (writingWriters > 0 || (preferWriter && waitingWriters > 0)) {wait();}readingReaders++; // (A)實際正在讀取的線程數(shù)量加1}public synchronized void readUnlock() {readingReaders--; // (A)實際正在讀取的線程數(shù)量減1preferWriter = true; //read處理后優(yōu)先處理writenotifyAll();}public synchronized void writeLock() throws InterruptedException {waitingWriters++; // (B)正在等待寫入的線程數(shù)量加1try {while (readingReaders > 0 || writingWriters > 0) {wait();}} finally {waitingWriters--; // (B)正在等待寫入的線程數(shù)量減1}writingWriters++; // (C)實際正在寫入的線程數(shù)量加1}public synchronized void writeUnlock() {writingWriters--; // (C)實際正在寫入的線程數(shù)量減preferWriter = false; //write處理后優(yōu)先處理readnotifyAll();} }
轉(zhuǎn)載于:https://www.cnblogs.com/cxccbv/archive/2009/05/08/1452927.html
總結(jié)
以上是生活随笔為你收集整理的模式6--ReadWriteLock的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 电表开户需要多少钱?
- 下一篇: 上海欢乐谷有哪些项目适合小孩子玩