我原想用这段代码看到写饥饿的情况,结果发现写的执行次数会比读还多。百思不得其解。
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class Main {
public static void main(String[] args) throws InterruptedException {
Operator operator = new Operator();
//启动100个读线程
for (int i = 0; i < 100; i++) {
new Thread(()->{
while (true){
try {
operator.read();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
//启动100个写线程
for (int i = 0; i < 100; i++) {
new Thread(()->{
while (true){
try {
operator.write();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
}
}
class Operator{
ReentrantReadWriteLock reentrantReadWriteLock;
Lock readLock;
Lock writeLock;
public Operator() {
reentrantReadWriteLock = new ReentrantReadWriteLock();
readLock = reentrantReadWriteLock.readLock();
writeLock = reentrantReadWriteLock.writeLock();
}
public void read() throws InterruptedException {
readLock.lock();
try {
System.out.print("R");
Thread.sleep(1000);
System.out.print ("r");
} finally {
readLock.unlock();
}
}
public void write() throws InterruptedException {
writeLock.lock();
try {
System.out.print("O");
Thread.sleep(1000);
System.out.print("o");
} finally {
writeLock.unlock();
}
}
}