wozhu_csdn 2022-01-03 18:41 采纳率: 0%
浏览 13

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

  • 写回答

2条回答 默认 最新

  • 关注

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

    评论 编辑记录

报告相同问题?

问题事件

  • 创建了问题 1月3日

悬赏问题

  • ¥15 is not in the mmseg::model registry。报错,模型注册表找不到自定义模块。
  • ¥15 安装quartus II18.1时弹出此error,怎么解决?
  • ¥15 keil官网下载psn序列号在哪
  • ¥15 想用adb命令做一个通话软件,播放录音
  • ¥30 Pytorch深度学习服务器跑不通问题解决?
  • ¥15 部分客户订单定位有误的问题
  • ¥15 如何在maya程序中利用python编写领子和褶裥的模型的方法
  • ¥15 Bug traq 数据包 大概什么价
  • ¥15 在anaconda上pytorch和paddle paddle下载报错
  • ¥25 自动填写QQ腾讯文档收集表