I am a Master Student and I have to write code for the classic reader writer problem with a limited number of readers at a time. I have to write in Java using multithreading. But without semaphore. Only using monitors and the keyword synchronized. I have already get some code that working. But I have to change it to limit to 3 readers at a time. And I dont know how...
My code is below There is no priority to readers or writer but I don't want any staravation too. But at first step I just want to play with sleeping to let my writer access the journal. Thanks (I have to do this in the next hours)
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 () ;
}
}
}