In: Computer Science
Implement a solution java solution for creating two writer threads and four reader threads
Following is the source code :
/** WriterThread.java **/
public class WriterThread extends Thread
{
private static int writers = 0; // number of writers
private int number;
private Library library;
/**
This is how to create a writer thread for the specified library.
@param library braryli to which to write.
*/
public WriterThread(Library library)
{
this.library = library;
this.number = WriterThread.writers++;
}
/**
Running the thread
*/
public void run()
{
while (true)
{
final int THREAD_DELAY = 10000;
try
{
Thread.sleep((int) (Math.random() * THREAD_DELAY));
}
catch (InterruptedException e) {}
this.library.write(this.number);
}
}
}
/** ReaderThread.java **/
public class ReaderThread extends Thread
{
private static int readers = 0;
private int number;
private Library library;
/**
This is how to create a reader thread for the library
*/
public ReaderThread(Library library)
{
this.library = library;
this.number = ReaderThread.readers++;
}
/**
running a thread
*/
public void run()
{
while (true)
{
final int THREAD_DELAY = 10000;
try
{
Thread.sleep((int) (Math.random() * THREAD_DELAY));
}
catch (InterruptedException e) {}
this.library.read(this.number);
}
}
}
/**Library.java **/
public class Library
{
private int readers; // number of active readers
/**
Initializes the library.
*/
public Library()
{
this.readers = 0;
}
/**
Reading from the library.
@param number Number of the reader.
*/
public void read(int number)
{
synchronized(this)
{
this.readers++;
System.out.println("Reader thread" + number + " starts reading.");
}
final int THREAD_DELAY = 5000;
try
{
Thread.sleep((int) (Math.random() * THREAD_DELAY));
}
catch (InterruptedException e) {}
synchronized(this)
{
System.out.println("Reader thread" + number + " stops reading.");
this.readers--;
if (this.readers == 0)
{
this.notifyAll();
}
}
}
/**
Writing to the library .
@param number Number of the writer thread.
*/
public synchronized void write(int number)
{
while (this.readers != 0)
{
try
{
this.wait();
}
catch (InterruptedException e) {}
}
System.out.println("Writer thread " + number + " starts writing.");
final int DELAY = 5000;
try
{
Thread.sleep((int) (Math.random() * DELAY));
}
catch (InterruptedException e) {}
System.out.println("Writer thread" + number + " stops writing.");
this.notifyAll();
}
}
/** Test.java **/
public class Test {
/**
Start two reader thread and 4 writer threads from main class .
*/
public static void main(String[] args)
{
{
final int READERS = 2;
final int WRITERS = 4;
Library library = new Library();
for (int i = 0; i < READERS; i++)
{
new ReaderThread(library).start();
}
for (int i = 0; i < WRITERS; i++)
{
new WriterThread(library).start();
}
}
}
}