Java多線程14 讀寫鎖分離設(shè)計模式

Java多線程目錄
1.read read 并行化
2.read write 不允許
3.write write 不允許

public class ReaderWorker extends Thread {

    private final SharedData data;

    public ReaderWorker(SharedData data) {
        this.data = data;
    }

    @Override
    public void run() {
        while (true) {
            try {
                char[] readBuf = data.read();
                System.out.println(Thread.currentThread().getName() + " reads " + String.valueOf(readBuf));

            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }
}
public class ReadWriteLock {

    /**
     * 當前有幾個線程 在對它進行讀操作
     */
    private int readingReaders = 0;
    /**
     * 當前有幾個線程 等待讀操作
     */
    private int waitingReaders = 0;

    /**
     * 當前有幾個線程 正在寫操作
     */
    private int writingWriters = 0;
    /**
     * 當前有幾個線程 正在寫操作
     */
    private int waitingWriters = 0;

    /**
     * 偏向于寫
     */
    private boolean preferWriter = true;

    public ReadWriteLock() {
        this(true);
    }

    public ReadWriteLock(boolean preferWriter) {
        this.preferWriter = preferWriter;
    }

    public synchronized void readLock() throws InterruptedException {
        this.waitingReaders++;
        try {
            /**
             * 讓寫的線程先運行
             */
            while (writingWriters > 0||(preferWriter&&waitingWriters>0)) {
                this.wait();
            }
            this.readingReaders++;
        } finally {
            this.waitingReaders--;
        }
    }

    public synchronized void readUnLock() {
        this.readingReaders--;
        this.notifyAll();
    }

    public synchronized void writeLock() throws InterruptedException {
        this.waitingWriters++;
        try {

            while (readingReaders > 0 || writingWriters > 0) {
                this.wait();
            }

            this.writingWriters++;
        } finally {
            this.waitingWriters--;
        }
    }

    public synchronized void writeUnlock() {
        this.writingWriters--;
        this.notifyAll();
    }
}
public class SharedData {

    private final char[] buffer;
    private final ReadWriteLock lock = new ReadWriteLock();

    public SharedData(int size) {
        this.buffer = new char[size];
        for (int i = 0; i < size; i++) {
            this.buffer[i] = '*';
        }
    }

    public char[] read() throws InterruptedException {
        try {
            lock.readLock();
            return this.doRead();
        } finally {
            lock.readUnLock();
        }
    }

    public void write(char c) throws InterruptedException {
        try {
            lock.writeLock();
            this.doWrite(c);
        } finally {
            lock.writeUnlock();
        }
    }

    private void doWrite(char c) {
        for (int i = 0; i < buffer.length; i++) {
            buffer[i] = c;
            slowly(10);
        }
    }

    private char[] doRead() {
        char[] newBuf = new char[buffer.length];
        for (int i = 0; i < buffer.length; i++) {
            newBuf[i] = buffer[i];
        }
        slowly(50);
        return newBuf;
    }

    private void slowly(int millisecond) {
        try {
            Thread.sleep(millisecond);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

public class WriterWorker extends Thread {

    private static final Random random = new Random(System.currentTimeMillis());

    private final SharedData data;
    private final String filter;

    private int index = 0;

    public WriterWorker(SharedData data, String filter) {
        this.data = data;
        this.filter = filter;
    }

    @Override
    public void run() {

        try {

            while (true) {
                char c = nextChar();

                data.write(c);

                Thread.sleep(random.nextInt(1000));

            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private char nextChar() {

        char c = filter.charAt(index);
        index++;
        if (index >= filter.length())
            index = 0;
        return c;
    }
}
/**
 *
 * ReadWriteLock
 */
public class ReadWriteLockClient {
    public static void main(String[] args) {
        final  SharedData sharedData = new SharedData(10);

        new ReaderWorker(sharedData).start();
        new ReaderWorker(sharedData).start();
        new ReaderWorker(sharedData).start();
        new ReaderWorker(sharedData).start();
        new ReaderWorker(sharedData).start();
        new WriterWorker(sharedData,"123456").start();
        new WriterWorker(sharedData,"abcdef").start();
    }
}

結(jié)果

Thread-0 reads **********
Thread-1 reads **********
Thread-2 reads **********
Thread-3 reads **********
Thread-1 reads aaaaaaaaaa
Thread-3 reads aaaaaaaaaa
Thread-0 reads aaaaaaaaaa
Thread-2 reads aaaaaaaaaa
Thread-1 reads aaaaaaaaaa
Thread-2 reads aaaaaaaaaa
Thread-0 reads aaaaaaaaaa
Thread-3 reads aaaaaaaaaa
Thread-1 reads aaaaaaaaaa
Thread-3 reads aaaaaaaaaa
Thread-0 reads aaaaaaaaaa
Thread-2 reads aaaaaaaaaa
Thread-2 reads aaaaaaaaaa
Thread-0 reads aaaaaaaaaa
Thread-1 reads aaaaaaaaaa
Thread-3 reads aaaaaaaaaa
Thread-2 reads aaaaaaaaaa
Thread-0 reads aaaaaaaaaa
Thread-1 reads aaaaaaaaaa
Thread-3 reads aaaaaaaaaa
Thread-0 reads bbbbbbbbbb
Thread-1 reads bbbbbbbbbb
Thread-2 reads bbbbbbbbbb
Thread-3 reads bbbbbbbbbb
Thread-0 reads bbbbbbbbbb
Thread-1 reads bbbbbbbbbb
Thread-3 reads bbbbbbbbbb
Thread-2 reads bbbbbbbbbb
Thread-0 reads bbbbbbbbbb
Thread-1 reads bbbbbbbbbb
Thread-2 reads bbbbbbbbbb
Thread-3 reads bbbbbbbbbb
Thread-0 reads bbbbbbbbbb
Thread-1 reads bbbbbbbbbb
Thread-3 reads bbbbbbbbbb
Thread-2 reads bbbbbbbbbb
Thread-1 reads 3333333333
Thread-2 reads 3333333333
Thread-3 reads 3333333333
...... 省略
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市狠持,隨后出現(xiàn)的幾起案子彪杉,更是在濱河造成了極大的恐慌萄窜,老刑警劉巖梗掰,帶你破解...
    沈念sama閱讀 216,372評論 6 498
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件车柠,死亡現(xiàn)場離奇詭異霸饲,居然都是意外死亡它改,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,368評論 3 392
  • 文/潘曉璐 我一進店門慌核,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人申尼,你說我怎么就攤上這事垮卓。” “怎么了师幕?”我有些...
    開封第一講書人閱讀 162,415評論 0 353
  • 文/不壞的土叔 我叫張陵粟按,是天一觀的道長。 經(jīng)常有香客問我霹粥,道長灭将,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,157評論 1 292
  • 正文 為了忘掉前任后控,我火速辦了婚禮庙曙,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘浩淘。我一直安慰自己捌朴,他們只是感情好,可當我...
    茶點故事閱讀 67,171評論 6 388
  • 文/花漫 我一把揭開白布张抄。 她就那樣靜靜地躺著砂蔽,像睡著了一般。 火紅的嫁衣襯著肌膚如雪署惯。 梳的紋絲不亂的頭發(fā)上左驾,一...
    開封第一講書人閱讀 51,125評論 1 297
  • 那天,我揣著相機與錄音极谊,去河邊找鬼诡右。 笑死,一個胖子當著我的面吹牛怀酷,可吹牛的內(nèi)容都是我干的稻爬。 我是一名探鬼主播,決...
    沈念sama閱讀 40,028評論 3 417
  • 文/蒼蘭香墨 我猛地睜開眼蜕依,長吁一口氣:“原來是場噩夢啊……” “哼桅锄!你這毒婦竟也來了琉雳?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,887評論 0 274
  • 序言:老撾萬榮一對情侶失蹤友瘤,失蹤者是張志新(化名)和其女友劉穎翠肘,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體辫秧,經(jīng)...
    沈念sama閱讀 45,310評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡束倍,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,533評論 2 332
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了盟戏。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片绪妹。...
    茶點故事閱讀 39,690評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖柿究,靈堂內(nèi)的尸體忽然破棺而出邮旷,到底是詐尸還是另有隱情,我是刑警寧澤蝇摸,帶...
    沈念sama閱讀 35,411評論 5 343
  • 正文 年R本政府宣布婶肩,位于F島的核電站,受9級特大地震影響貌夕,放射性物質(zhì)發(fā)生泄漏律歼。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,004評論 3 325
  • 文/蒙蒙 一啡专、第九天 我趴在偏房一處隱蔽的房頂上張望险毁。 院中可真熱鬧,春花似錦植旧、人聲如沸辱揭。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,659評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽问窃。三九已至,卻和暖如春完沪,著一層夾襖步出監(jiān)牢的瞬間域庇,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,812評論 1 268
  • 我被黑心中介騙來泰國打工覆积, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留听皿,地道東北人。 一個月前我還...
    沈念sama閱讀 47,693評論 2 368
  • 正文 我出身青樓宽档,卻偏偏與公主長得像尉姨,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子吗冤,可洞房花燭夜當晚...
    茶點故事閱讀 44,577評論 2 353