實現ReadWriteLock鎖
主要lock代碼
//讀寫鎖
public class ReadWriteLock {
/**
* 正在讀的線程數
*/
private int readerReading = 0;
/**
* 等待讀的線程數
*/
private int readerWaiting = 0;
/**
* 正在寫的線程數
*/
private int writeWriting = 0;
/**
* 等待寫的線程數
*/
private int writeWaiting = 0;
/**
* 是否更偏愛寫鎖
*/
private boolean peferWrite;
public ReadWriteLock(){
this(true);
}
public ReadWriteLock(boolean peferWrite){
this.peferWrite = peferWrite;
}
public synchronized void readLock() throws InterruptedException {
//進來之後先將等待讀數量+1
this.readerWaiting++;
try{
while(writeWriting>0||(peferWrite&&writeWaiting>0)){
this.wait();
}
//正在讀鎖+1
this.readerReading++;
}finally {
//退出時將等待讀數量-1
this.readerWaiting--;
}
}
public synchronized void readUnlock(){
this.readerReading--;
this.notifyAll();
}
public synchronized void writeLock() throws InterruptedException {
this.writeWaiting++;
try{
while (writeWriting>0||readerReading>0){
this.wait();
}
this.writeWriting++;
}finally {
this.writeWaiting--;
}
}
public synchronized void writeUnlock(){
this.writeWriting--;
this.notifyAll();
}
}
接下來是測試類了,創建一個共享數據類,提供read和write方法
public class ShareDate {
private final char[] buffer;
private final ReadWriteLock lock = new ReadWriteLock();
public ShareDate(int size){
buffer = new char[size];
for (int i = 0; i < size; i++) {
buffer[i] = '*';
}
}
public void read(){
try {
lock.readLock();
System.out.println("Reader:"+ Arrays.toString(buffer));
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
lock.readUnlock();
}
}
public void write(String str){
for (int i = 0; i < str.length(); i++) {
this.doWrite(str.charAt(i));
}
}
private void doWrite(char c){
try {
lock.writeLock();
for (int i = 0; i < buffer.length; i++) {
buffer[i] = c;
}
System.out.println("Writer:"+ Arrays.toString(buffer));
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
lock.writeUnlock();
}
}
}
兩個線程類read和writer
public class WriteThread extends Thread {
private ShareDate shareDate;
private String str;
public WriteThread(ShareDate shareDate,String str){
this.shareDate = shareDate;
this.str = str;
}
@Override
public void run() {
while (true){
shareDate.write(str);
}
}
}
public class ReadThread extends Thread{
private ShareDate shareDate;
public ReadThread(ShareDate shareDate){
this.shareDate = shareDate;
}
@Override
public void run() {
while (true){
shareDate.read();
}
}
}
測試主類
public static void main(String[] args) {
ShareDate shareDate = new ShareDate(20);
new ReadThread(shareDate).start();
new ReadThread(shareDate).start();
new ReadThread(shareDate).start();
new ReadThread(shareDate).start();
new ReadThread(shareDate).start();
new ReadThread(shareDate).start();
new WriteThread(shareDate,"qwertyuiop").start();
new WriteThread(shareDate,"QWERTYUIOP").start();
}
完畢