1. 程式人生 > >圖解java多執行緒設計模式學習第六章Read-Write Lock模式

圖解java多執行緒設計模式學習第六章Read-Write Lock模式

學生們正在一起看老師在黑板上寫的板書。這時,老師想插掉板書,再寫新的內容。而學生們說道:“”老師,我們還沒看完了,請先不要摖掉“”。於是,老師會等待大家都看完。

當執行緒“”讀取“”例項的狀態時,例項的狀態不會發生變化。例項的狀態僅線上程執行“”寫入“”操作時才會發生變化。從例項的狀態變化這個觀點來看,“”讀取“”和“”寫入“”有著本質的區別。

在Read-Write Lock模式中,讀取操作和寫入操作是分開考慮的。在執行讀取操作之前,執行緒必須獲取用於讀取的鎖。而在執行寫入操作之前,執行緒必須獲取用於寫入的鎖。

由於當前執行緒執行讀取操作時,例項的狀態不會發生變化,所以一個執行緒正在寫入時,其他執行緒不可以讀取或寫入。

一般來說,執行互斥處理會降低程式效能。但如果把針對寫入的互斥處理和針對讀取的互斥處理分開來考慮,則可以提高程式效能。

package com.readwritelock;
public class Data {
    private final char[] buffer;
    private final ReadWriteLock lock = new ReadWriteLock();
    public Data(int size) {
        this.buffer = new char[size];
        for (int i = 0; i < buffer.length; i++) {
            buffer[i] = '*';
        }
    }
    public char[] read() throws InterruptedException {
        lock.readLock();
        try {
            return doRead();
        } finally {
            lock.readUnlock();
        }
    }
    public void write(char c) throws InterruptedException {
        lock.writeLock();
        try {
            doWrite(c);
        } finally {
            lock.writeUnlock();
        }
    }
    private char[] doRead() {
        char[] newbuf = new char[buffer.length];
        for (int i = 0; i < buffer.length; i++) {
            newbuf[i] = buffer[i];
        }
        slowly();
        return newbuf;
    }
    private void doWrite(char c) {
        for (int i = 0; i < buffer.length; i++) {
            buffer[i] = c;
            slowly();
        }
    }
    private void slowly() {
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
        }
    }
}

package com.readwritelock;

public class ReaderThread extends Thread {
    private final Data data;
    public ReaderThread(Data data) {
        this.data = data;
    }
    public void run() {
        try {
            while (true) {
                char[] readbuf = data.read();
                System.out.println(Thread.currentThread().getName() + " reads " + String.valueOf(readbuf));
            }
        } catch (InterruptedException e) {
        }
    }
}

package com.readwritelock;
public final class ReadWriteLock {
    private int readingReaders = 0; // (A)…實際正在讀取中的執行緒個數
    private int waitingWriters = 0; // (B)…正在等待寫入的執行緒個數
    private int writingWriters = 0; // (C)…實際正在寫入中的執行緒個數
    private boolean preferWriter = true; // 若寫入優先,則為true

    public synchronized void readLock() throws InterruptedException {
        while (writingWriters > 0 || (preferWriter && waitingWriters > 0)) {
            wait();
        }
        readingReaders++;                       // (A) 實際正在讀取的執行緒個數加1
    }

    public synchronized void readUnlock() {
        readingReaders--;                       // (A) 實際正在讀取的執行緒個數減1
        preferWriter = true;
        notifyAll();
    }

    public synchronized void writeLock() throws InterruptedException {
        waitingWriters++;                       // (B) 正在等待寫入的執行緒個數加1
        try {
            while (readingReaders > 0 || writingWriters > 0) {
                wait();
            }
        } finally {
            waitingWriters--;                   // (B) 正在等待寫入的執行緒個數減1
        }
        writingWriters++;                       // (C) 實際正在寫入的執行緒個數加1
    }

    public synchronized void writeUnlock() {
        writingWriters--;                       // (C) 實際正在寫入的執行緒個數減1
        preferWriter = false;
        notifyAll();
    }
}

package com.readwritelock;
import java.util.Random;

public class WriterThread extends Thread {
    private static final Random random = new Random();
    private final Data data;
    private final String filler;
    private int index = 0;
    public WriterThread(Data data, String filler) {
        this.data = data;
        this.filler = filler;
    }
    public void run() {
        try {
            while (true) {
                char c = nextchar();
                data.write(c);
                Thread.sleep(random.nextInt(3000));
            }
        } catch (InterruptedException e) {
        }
    }
    private char nextchar() {
        char c = filler.charAt(index);
        index++;
        if (index >= filler.length()) {
            index = 0;
        }
        return c;
    }
}

package com.readwritelock;

public class Main {
    public static void main(String[] args) {
        Data data = new Data(10);
        new ReaderThread(data).start();
        new ReaderThread(data).start();
        new ReaderThread(data).start();
        new ReaderThread(data).start();
        new ReaderThread(data).start();
        new ReaderThread(data).start();
        new WriterThread(data, "ABCDEFGHIJKLMNOPQTSTUVWXYZ").start();
        new WriterThread(data, "abcdefghijklmnopqrstuvwxyz").start();
    }
}