我对我在编程语言类的概念中学习的新概念感到有点困惑。任何信息都会很棒。读者作家问题如下:
这个经典问题需要进程读取和写入同步。因此,在定义和创建用于读写的线程之前,需要一个同步控制器。以下是控制器类(有两种方法可供您实现)。为了简化编程,当您编写用于读写的线程类(例如,三个读取器和一个写入器)时,您只需在开始读取或写入时象征性地打印消息,并在完成读取或写入时打印另一条消息(因此没有必要创建每个线程读取或写入的实际共享内容。
这就是我所拥有的。我想我错过了线程的基本内容。请注意,除了必须由我实现startWriting()和stopWriting()之外,还给出了控制器类和方法。谢谢。
class Controller {
private int activeReaders = 0;
private boolean writerPresent = false;
protected boolean writeCondition() {
return activeReaders == 0 && !writerPresent;
}
protected boolean readCondition() {
return !writerPresent;
}
protected synchronized void startRead() {
while (!readCondition())
try { wait(); } catch (InterruptedException ex) {}
++activeReaders;
}
protected synchronized void stopRead() {
--activeReaders;
notifyAll();
}
protected synchronized void startWriting(){
writerPresent = true;
System.out.println("Writing has begun");
}
protected synchronized void stopWriting(){
System.out.println("Reading is now available");
writerPresent = false;
}
public static void main(String [] args){
Controller c = new Controller();
Thread tRead1 = new Thread(new Runnable() {
@Override
public void run(){
c.startRead();
System.out.println("Reader 1 has started reading");
c.stopRead();
System.out.println("Reader 1 has stopped reading");
}
});
Thread tRead2 = new Thread(new Runnable() {
@Override
public void run(){
c.startRead();
System.out.println("Reader 2 has started reading");
c.stopRead();
System.out.println("Reader 2 has stopped reading");
}
});
Thread tRead3 = new Thread(new Runnable() {
@Override
public void run(){
c.startRead();
System.out.println("Reader 3 has started reading");
c.stopRead();
System.out.println("Reader 3 has stopped reading");
}
});
Thread tWrite1 = new Thread(new Runnable() {
@Override
public void run(){
c.startWriting();
c.stopWriting();
}
});
tRead1.start();
tRead2.start();
tWrite1.start();
try {
tWrite1.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
tRead3.start();
}
}
答案 0 :(得分:0)
首先,我建议你转到javadocs并阅读wait,notify和notifyall的方法定义。这是Java中的基本等待/锁定/通知系统。
就读者和作家而言,如果没有可用的内容,读者都应该从作者那里阅读,并使用作者wait
暂停。如果您有多个编写器,则可以对等待消息队列的读者执行相同的操作。当作者写入并且有更多数据要由读者使用时,它应该在自己(作者)上调用notify
来唤醒一个消费者以获取新数据。
并告诉您何时可以/应该使用notifyAll:
Thread.join通过在正在加入的Thread上调用wait
来工作。线程死亡后,线程调用notifyAll
唤醒所有等待它完成的线程。