gpt4 book ai didi

java - 为什么读者和作者众多,却陷入僵局

转载 作者:行者123 更新时间:2023-12-01 19:51:14 25 4
gpt4 key购买 nike

我正在练习readers and writers problem并提出以下解决方案。但是,在打印出以下结果后,程序会自行阻塞。

$ Read content: planets

我的想法是 first solution 的修改版本。使用 2 个信号量,一个称为 readMutex,确保一次只有一个读取线程更新 numOfReaders,而另一个信号量称为 accessToResource,确保当读取器正在阅读内容,作者应该等待。这是我的代码。

import java.util.concurrent.Semaphore;

public class ReadersAndWriters {
public static final Semaphore accessToResource = new Semaphore(1, true);
public static final Semaphore readMutex = new Semaphore(1, true);
public static String content = "planets";
public static int numOfReaders;

static class Reader extends Thread {
void read() {
try {
readMutex.acquire();
numOfReaders++;
if (numOfReaders == 1) {
accessToResource.acquire();
}
readMutex.release();

// read content, not a critical section
System.out.println("Read content:\t" + content);

readMutex.acquire();
numOfReaders--;
if (numOfReaders <= 0) {
accessToResource.release();
}
readMutex.release();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}

@Override
public void run() {
read();
}
}

static class Writer extends Thread {
String text;

Writer(String text) {
this.text = text;
}

void write() {
try {
readMutex.acquire();
accessToResource.acquire();

// critical section
content = text;
System.out.println("Content changed:\t" + content);
// end of critical section

accessToResource.release();
readMutex.release();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}

@Override
public void run() {
write();
}
}

public static void main(String[] args) {
Reader t1 = new Reader();
Reader t2 = new Reader();
Writer t3 = new Writer("stars");
Reader t4 = new Reader();
Writer t5 = new Writer("restaurant at the end of universe");
Reader t6 = new Reader();
Reader t7 = new Reader();
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
t6.start();
t7.start();
}
}

最佳答案

当一个Reader已获取accessToResource并尝试获取readMutex时:

if (numOfReaders == 1) {
accessToResource.acquire();
}
readMutex.release();

System.out.println("Read content:\t" + content);

readMutex.acquire(); // -------> here

当另一个Writter已获取readMutex并尝试获取accessToResource时:

readMutex.acquire();
accessToResource.acquire(); // ------> here

发生死锁。

由于 accessToResourcereadMutex 的许可为 1,因此 Reader 都没有权限作家可以继续前进。

关于java - 为什么读者和作者众多,却陷入僵局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51268230/

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