Question

In: Computer Science

Implement a solution java solution for creating two writer threads and four reader threads

Implement a solution java solution for creating two writer threads and four reader threads

Solutions

Expert Solution

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();
            }
        }
    }
}

Related Solutions

Write a C-program to implement the Reader/Writer model for the attached pseudocode modified to produce only...
Write a C-program to implement the Reader/Writer model for the attached pseudocode modified to produce only one million output instead of an infinite amount. Use pthreads and Linux semaphores. Include ten readers with one writer. The writer should produce one million outputs. Verify that the readers receive an equal share of the information produced. Meaning each reader receives about 100,000 of information. Explain your results regardless of the balance. No use mutex or monitor functions. ****PSEUDOCODE**** /* program readersandwriters */...
Write a C++ program where you implement a synchronized multithreaded version of HAPPY with four threads....
Write a C++ program where you implement a synchronized multithreaded version of HAPPY with four threads. The program will take in an array from 1 to n (n = 50) and will be passed to four different threads: If the current number is divisible by 2, then print HAP If the current number is divisible by 5, then print PY If the current number is divisible by both 2 and 5, then print HAPPY If the number is neither divisible...
DO THIS IN JAVA Write a complete Java program. the program has two threads. One thread...
DO THIS IN JAVA Write a complete Java program. the program has two threads. One thread prints all capital letters 'A' to'Z'. The other thread prints all odd numbers from 1 to 21.
Starting out with Python Files and Exceptions - Random Number Writer, Reader, and Exception Handler In...
Starting out with Python Files and Exceptions - Random Number Writer, Reader, and Exception Handler In this assignment, you will be writing a series of random numbers to a file, reading the file, and handling exceptions. Begin by writing a program that writes a series of random numbers to a file. Each random number should be in the range of 1 through 100. The application should let the user specify how many random numbers the file will hold. Next, write...
Please show solution and comments for this data structure using java.​ Implement a program in Java...
Please show solution and comments for this data structure using java.​ Implement a program in Java to convert an infix expression that includes (, ), +, -, *,     and / to postfix expression. For simplicity, your program will read from standard input (until the user enters the symbol “=”) an infix expression of single lower case and the operators +, -, /, *, and ( ), and output a postfix expression.
In Java In this lab we will creating two linked list classes: one that is a...
In Java In this lab we will creating two linked list classes: one that is a singly linked list, and another that is a doubly linked list ( This will be good practice for your next homework assignment where you will build your own string class using arrays and linked list ) . These LinkedList classes should both be generic classes. and should contain the following methods: Print Add - Adds element to the end of the linked list. IsEmpty...
Create a Java application that will exhibit concurrency concepts. Your application should create two threads that will act as counters.
JAVACreate a Java application that will exhibit concurrency concepts. Your application should create two threads that will act as counters. One thread should count up to 20. Once thread one reaches 20, then a second thread should be used to count down to 0.
The answer should be in JAVA. You will design and implement two classes to support a...
The answer should be in JAVA. You will design and implement two classes to support a client program, RockPaperScissorsGame.java, to simulate Rock-Paper-Scissors game. Read and understand the client program to find out the requirements for the HandShape and Player classes. The rules of the Rock-Paper-Scissors game are:     Scissors✌️ beats Paper✋ that beats Rock✊ that beats Scissors✌️ Additionally, to simplify the game logic (and complexify a little bit the HandSahpe class) , two players cannot show the same hand shape....
The answer should be in JAVA. You will design and implement two classes to support a...
The answer should be in JAVA. You will design and implement two classes to support a client program, RockPaperScissorsGame.java, to simulate Rock-Paper-Scissors game. Read and understand the client program to find out the requirements for the HandShape and Player classes. The rules of the Rock-Paper-Scissors game are:     Scissors✌️ beats Paper✋ that beats Rock✊ that beats Scissors✌️ Additionally, to simplify the game logic (and complexify a little bit the HandSahpe class) , two players cannot show the same hand shape....
Intro to Java. Creating random SSN
Create a Java program which includes the following: Uses a random value as well as manipulates string and character objects in order to make an SS# (xxx-xx-xxxx).First 3 Numbers: Create a three digit random integer named FirstThree in the range of 100- 999. (10 Points)Second 2 Numbers: Create a two digit number named SecondTwo by using FirstThree as follows: (10 Points) If FirstThree is 550 or less then create a 2 digit string using the name StringFirstThree from the first 2 digits of FirstThree otherwise create a 2...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT