ReentrantReadWriteLock 读写线程数相同的情况下,没有出现写饥饿,甚至写的执行次数还多于读操作。原因是什么?

我原想用这段代码看到写饥饿的情况,结果发现写的执行次数会比读还多。百思不得其解。


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();
        }
    }
}

非公平锁导致的,写锁一直在重入,抢占资源。

仔细再研究下吧,相信你少年!加油