我是一名硕士生,我必须一次为有限数量的读者编写经典读写器问题的代码。我必须使用多线程在 Java 中编写。但是没有信号量。仅使用监视器和关键字同步。我已经得到了一些有效的代码。但我必须将其更改为一次限制为 3 个读者。而且我不知道怎么...
我的代码在下面 读者或作者没有优先权,但我也不想挨饿。但在第一步我只想玩睡觉让我的作家访问日记。谢谢(我必须在接下来的几个小时内这样做)
class Journal {
public static final int PAUSE = 5;
private int nbReaders ;
private boolean Reading,Writing ;
public Journal () {nbReaders = 0 ;Reading = false ;Writing = false ;}
public synchronized int demandeReading () {
while (Writing == true)
try{ wait(); } catch(InterruptedException e) {}
if (++nbReaders == 1)
Reading = true ;
return nbReaders ;
}
public synchronized int finReading () {
if (--nbReaders == 0)
Reading = false ;
notifyAll();
return nbReaders ;
}
public synchronized void demandeWriting () {
while ( Reading == true || Writing == true )
try{ wait () ; }catch(InterruptedException e) {}
Writing = true ;
}
public synchronized void finWriting() { Writing = false ; notifyAll () ; }
public static void travaille(){
int tpsPause = (int) ( PAUSE * Math.random () ) ;
try { Thread.sleep ( tpsPause * 100 ) ; } catch(InterruptedException e) {}
}
}
class Reader extends Thread {
private int nbReadings = 5;
private Journal journal ;
public Reader ( Journal j ) { journal = j ; }
public void run () {
int nbReaders ;
while ( nbReadings > 0 ) {
nbReaders = journal.demandeReading () ;
System.out.println( Thread.currentThread().getName() + " lit ... " +nbReaders + " Reading en cours" ) ;
Journal.travaille () ;
nbReaders = journal.finReading () ;
nbReadings -- ;
System.out.println( Thread.currentThread().getName() + " ne lit plus ..." +nbReaders + " Readings en cours" ) ;
}
}
}
class Writer extends Thread {
private int nbWritings = 2;
private Journal journal;
public Writer(Journal j) {journal = j;}
public void run() {
while (nbWritings > 0) {
journal.demandeWriting();
System.out.println(Thread.currentThread().getName() + " ecrit ...");
Journal.travaille();
journal.finWriting();
nbWritings--;
}
}
}
class ReadersWriterCours {
static Journal journal = new Journal ( ) ;
public static void main ( String [] args ) {
Writer tabW [] = new Writer [ 5 ] ;
Reader tabR [] = new Reader [ 5 ] ;
for (int i = 0 ; i < 5 ; i ++ ) {
tabW[ i ] = new Writer ( journal ) ;
tabR[ i ] = new Reader ( journal ) ;
tabW [ i ].start () ;
tabR [ i ].start () ;
}
}
}