使用Java实现了读优先和写优先的读写者问题, 使用管程的方式(封装成类)控制互斥和同步
读者优先
import java.util.concurrent.locks.*;
public class ProducerAndConsumer {
public static void main(final String[] args) {
final fileRW f = new fileRW();
for (int i = 0; i < 4; i++) {
new Thread(
()->f.write()
).start();
}
for (int i = 0; i < 10; i++) {
new Thread(
()->f.read()
).start();
}
for (int i = 0; i < 10; i++) {
new Thread(
()->f.read()
).start();
}
}
}
class fileRW {
// 读优先只需要一个条件变量 但是需要记录等待读
private final Lock lock = new ReentrantLock();
private int readCnt = 0, writeCnt = 0, waitRead = 0;
private final Condition fileAccess = lock.newCondition();
public void read() {
enterRead(); // 读写互斥 如果有正在写 阻塞
System.out.println(Thread.currentThread().getName()
+ " is Reading."
+ " Reader: " + readCnt
+ " WaitingReader:" + waitRead);
try {
Thread.sleep(1000);} catch(InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " read done");
leaveRead(); // 如果没有正在读或等待读 唤醒写
}
public void write() {
// 如果有写 或等待读 正在读 阻塞 这里是读优先的体现 读者可以通过waitRead 插队
enterWrite();
System.out.println(Thread.currentThread().getName() + " is Writing");
try {
Thread.sleep(2000);}