我试图使用通知和等待来实现读写器。但我想我被困住了。
我的顺序是这样的。
RRRRRRRRRRWWWWWWWWWW
如果 main 启动时先调用 reader,就会发生这种情况。
或者
WWWWWWWRRRRRRRRRRR
。如果 main 程序首先调用 writer,就会发生这种情况。
看起来读取通知根本不起作用。编写器线程永远不会执行。
如果我在 run 方法中使 while 循环无限运行,那么它只是
RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR........
。作家没有机会写作。
你能看一下这个吗?
数据类
public class Data {
private int q ;
private boolean isAnyOneReading;
public Data() {
}
public void readQ() {
synchronized (this){
isAnyOneReading = true;
System.out.println("Read start "+q);
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (this){
isAnyOneReading = false;
System.out.println("Read end "+q);
notifyAll();
}
}
public synchronized void writeQ(int q) {
System.out.println(isAnyOneReading);
while (isAnyOneReading){
try{
wait();
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("Done");
Thread.currentThread().interrupt();
}
}
System.out.println("Write start "+q);
this.q = q;
try{
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
System.out.println("Write end "+q);
notifyAll();
}
}
读者课
public class Reader implements Runnable {
private Data data;
private Thread readerThread;
public Reader(Data data) {
this.data = data;
readerThread = new Thread(this, "ReaderThread");
}
void startThread(){
readerThread.start();
}
@Override
public void run() {
int i = 0 ;
while (i != 5){
data.readQ();
i++;
}
}
}
作家类
public class Writer implements Runnable{
private Data data;
private Thread writerThread;
public Writer(Data data) {
this.data = data;
writerThread = new Thread(this,"WriterThread," );
}
void startThread(){
writerThread.start();
}
@Override
public void run() {
int i = 0 ;
int j = 0 ;
while (j != 5){
data.writeQ(i++);
// i++;
j++;
}
}
}
主类
public class ReaderWriterDemo {
public static void main(String[] args) {
Data data = new Data();
Reader reader = new Reader(data);
Writer writer = new Writer(data);
reader.startThread();
writer.startThread();
}
}
最佳答案
尝试从 Data 类中删除 Thread.sleep。 并像这样在 run 方法中添加 Thread.sleep 。 (粘贴一个例子):
@Override
public void run() {
int i = 0;
while (i != 5) {
data.readQ();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
i++;
}
}
}
关于java - java中读写器的实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60359704/