gpt4 book ai didi

java - 读者/作者问题的优先级

转载 作者:行者123 更新时间:2023-12-01 15:48:53 29 4
gpt4 key购买 nike

我为 Java 中的读写器问题开发了一个解决方案(有关此的一些信息 http://lass.cs.umass.edu/~shenoy/courses/fall08/lectures/Lec11.pdf )。

但是我不确定如何修改代码以有利于作者或给予读者和作者相同的优先级。我的代码属于什么类型的问题?我该如何看待它?

public class ReaderWriter{


int numberOfReaders;
int numberOfWriters;

public ReaderWriter(){
this.numberOfReaders = 0;
this.numberOfWriters = 0;
}

public synchronized void requestRead(){
while(this.numberOfWriters > 0)
wait();

this.numberOfReaders++;
}

public synchronized void releaseRead(){
this.numberOfReaders--;
notifyAll();
}

public synchronized void requestWrite(){
while(this.numberOfReaders > 0 || this.numberOfWriters > 0)
wait();

this.numberOfWriters++;
}

public synchronized void releaseWrite(){
this.numberOfWriters--;
notifyAll();
}
}

最佳答案

你的版本有利于读者(并且可能会让作家挨饿)。这是一个有利于作家的修改版本(并且可能会让读者挨饿):

    int numberOfReaders;
    int numberOfWriters;
int numberOfRequestedWriters; // ++

    public ReaderWriter(){
        this.numberOfReaders = 0;
        this.numberOfWriters = 0;
this.numberOfRequestedWriters = 0; // ++
    }

    public synchronized void requestRead(){
        while(this.numberOfWriters > 0 // --
|| this.numberOfRequestedWriters > 0) // ++
            wait();

        this.numberOfReaders++;
    }

    public synchronized void releaseRead(){
        this.numberOfReaders--;
        notifyAll();
    }

    public synchronized void requestWrite(){
this.numberOfRequestedWriters++; // ++
        while(this.numberOfReaders > 0 || this.numberOfWriters > 0)
            wait();
this.numberOfRequestedWriters--; // ++

        this.numberOfWriters++;
    }

    public synchronized void releaseWrite(){
        this.numberOfWriters--;
        notifyAll();
    }
}

关于java - 读者/作者问题的优先级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6531163/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com