Question

In: Advanced Math

Hello, I need this done with Java and ran in Eclipse if possible. A university wants...

Hello, I need this done with Java and ran in Eclipse if possible.

A university wants to demonstrate its political correctness by applying the Supreme Court’s “Separate but equal is inherently unequal” doctrine to gender as well as race. As such, the university has decided that both genders will use the same bathroom facilities. However, in order to preserve some tradition, it decrees that when a woman is in the bathroom, only other women may enter, and when a man is in the bathroom, only other men may enter. Each politically correct bathroom will have a sign on the outside indicating what state the bathroom is in; Empty, Women Present, or Men Present.

Your job is to implement a multi-threaded simulation of this politically correct bathroom. You may use whatever counters and synchronization mechanisms you need to make sure that your politically correct bathroom works according to the university decree.

Your implementation must generate some status report whenever anyone enters or leaves the bathroom, which should include the sex of the person entering or leaving. This status report should include the state of the bathroom, the number of men and/or women waiting, and the number and sex of the occupants currently in the bathroom.

Once a person (thread) enters the bathroom, that person’s stay in the bathroom should be determined by a random number. The minimum stay should be 2 seconds, and the maximum stay should be 5 seconds.

Once a person (thread) has left the bathroom, use random numbers to determine when that thread will try to gain access again. I suggest that the wait should range from 4 seconds to 10 seconds.

Your program should start 5 male threads and 5 female threads. Each thread should visit the bathroom 10 times. Analyze the output to make sure things are working correctly. Capture a sample of your program’s status reports. Also, print out your source code. Demonstrate your program to the professor, and get a sign off.

Basic Program Structure for PCB (Politically Correct Bathroom)

PCB Class

This class really does all the work of synchronizing access to the PCB. The first question to ask is what information the PCB needs to keep. The PCB has a state, which reflects whether it is empty or whether there are males or females inside. It also must keep track of the number of occupants which are inside, and the number who are waiting to get inside. There can be males or females inside or waiting.

The PCB must also have a means of blocking a thread that is trying to gain access if the state of the PCB does not permit access for this thread at this time. In order to block a thread, the PCB can use the wait method, which will be used to block threads that must wait until the state of the PCB permits access. The PCB should keep a counter which indicates how many males or females are blocked and waiting to get into the PCB.

Since the PCB has multiple member variables which must be read and written by multiple threads, we must synchronize access to these member variables by making the methods of this class synchronized methods.

The constructor for the PCB class must initialize all member variables, including all the state and counter variables.

There should be a maleEnters( ) method and a femaleEnters( ) method. These methods check the state to see whether the male or female thread is allowed to enter or must be blocked. Remember, reading and/or writing the member variables must be done inside a critical section which is protected by the synchronized methods. State and/or counter variables must be updated appropriately. If the male or female must wait to enter, the wait method is used to block the thread. Returning from one of these methods indicates that the thread was successful in entering the PCB.

There should also be a femaleExits( ) method and a maleExits( ) method. These methods update the counter and state member variables appropriately. If the thread exiting the bathroom is the last one out, the state member variable must change, and any waiting threads must be unblocked so that they can attempt to enter again. The notifyAll method can be used to wake up all the threads that are blocked and waiting to get into the PCB.

Remember that something in your simulation must output the state and counter info frequently, or whenever any thread enters or exits the PCB.

MaleThread and FemaleThread Classes

These classes contain the code that simulates the actions of a male or female thread entering and exiting the PCB. These two classes can either inherit from the Thread class or implement the Runnable interface. The constructor for these two classes should accept a PCB object so that all the male and female threads are using the same PCB object. The run method of these two classes should contain a loop which is executed 10 times. Inside the loop, a thread would sleep for a random amount of time between 4 and 10 seconds, and then call the appropriate entry method on the PCB. Once that method returns, the thread has gained access to the PCB and should wait for between 2 and 5 seconds before calling the appropriate exit method on the PCB object.

Main Test Program

This program controls the simulation. The main program must create a PCB object to be used by the male and female threads. It must also create 5 MaleThread objects and 5 FemaleThread objects and start all the male and female threads executing.

It is up to you how to display the output from your simulation. You can use a console window and report the status every time a thread enters, starts waiting, stops waiting, or exits the PCB object. Or you can use a simple GUI and use the main thread to periodically (every 100 msec) update a display that shows in some way the threads that are in the PCB or that are waiting to get in, and whether they are male or female threads.

Solutions

Expert Solution

SOLUTION:

Given That data  A university wants to demonstrate its political correctness by applying the Supreme Court’s “Separate but equal is inherently unequal” doctrine to gender as well as race. As such, the university has decided that both genders will use the same bathroom facilities. However, in order to preserve some tradition, it decrees that when a woman is in the bathroom, only other women may enter, and when a man is in the bathroom, only other men may enter. Each politically correct bathroom will have a sign on the outside indicating what state the bathroom is in; Empty, Women Present, or Men Present.

Your job is to implement a multi-threaded simulation of this politically correct bathroom. You may use whatever counters and synchronization mechanisms you need to make sure that your politically correct bathroom works according to the university decree.

Your implementation must generate some status report whenever anyone enters or leaves the bathroom, which should include the sex of the person entering or leaving. This status report should include the state of the bathroom, the number of men and/or women waiting, and the number and sex of the occupants currently in the bathroom.

Once a person (thread) enters the bathroom, that person’s stay in the bathroom should be determined by a random number. The minimum stay should be 2 seconds, and the maximum stay should be 5 seconds.

Once a person (thread) has left the bathroom, use random numbers to determine when that thread will try to gain access again. I suggest that the wait should range from 4 seconds to 10 seconds.

Your program should start 5 male threads and 5 female threads. Each thread should visit the bathroom 10 times. Analyze the output to make sure things are working correctly.

So

See the code below

USL class: USL.java

-----------------------------------------

package unisexlounge;

/**
* USL (UniSex Lounge) class
*
*/
public class USL {

   // enum for state of lounge
   public enum STATE {
       Empty, WomenPresent, MenPresent
   }

   // data members
   private STATE loungeState; // state of lounge
   private int malesInside; // males inside lounge
   private int malesWaiting; // males waiting to get inside lounge
   private int femalesInside; // females inside lounge
   private int femalesWaiting; // females waiting to get inside lounge

   /**
   * default constructor
   */
   public USL() {
       // TODO Auto-generated constructor stub
       loungeState = STATE.Empty;
       malesInside = 0;
       malesWaiting = 0;
       femalesInside = 0;
       femalesWaiting = 0;
   }

   /**
   * @return the state
   */
   STATE getState() {
       return loungeState;
   }

   /**
   * @param state
   *            the state to set
   */
   void setState(STATE state) {
       this.loungeState = state;
   }

   /**
   * @return the malesInside
   */
   int getMalesInside() {
       return malesInside;
   }

   /**
   * @param malesInside
   *            the malesInside to set
   */
   void setMalesInside(int malesInside) {
       this.malesInside = malesInside;
   }

   /**
   * @return the malesWaiting
   */
   int getMalesWaiting() {
       return malesWaiting;
   }

   /**
   * @param malesWaiting
   *            the malesWaiting to set
   */
   void setMalesWaiting(int malesWaiting) {
       this.malesWaiting = malesWaiting;
   }

   /**
   * @return the femalesInside
   */
   int getFemalesInside() {
       return femalesInside;
   }

   /**
   * @param femalesInside
   *            the femalesInside to set
   */
   void setFemalesInside(int femalesInside) {
       this.femalesInside = femalesInside;
   }

   /**
   * @return the femalesWaiting
   */
   int getFemalesWaiting() {
       return femalesWaiting;
   }

   /**
   * @param femalesWaiting
   *            the femalesWaiting to set
   */
   void setFemalesWaiting(int femalesWaiting) {
       this.femalesWaiting = femalesWaiting;
   }

   /**
   * maleEnters method
   *
   * @throws InterruptedException
   */
   public synchronized boolean maleEnters() throws InterruptedException {
       boolean maleEntered = false;
       STATE state = getState();
       if (state == STATE.Empty) {
           malesInside++;
           if (malesWaiting != 0)
               malesWaiting--;
           maleEntered = true;
           setState(STATE.MenPresent);
       } else if (state == STATE.MenPresent) {
           malesInside++;
           if (malesWaiting != 0)
               malesWaiting--;
           maleEntered = true;
       } else {
           malesWaiting++;
           int waitInterval = (int) (Math.random() * (10 - 4) + 4);
           // wait(waitInterval);
           Thread.sleep(waitInterval * 1000);
       }
       displayLoungeStatus();
       notifyAll();
       return maleEntered;
   }

   /**
   * femaleEnters method
   *
   * @throws InterruptedException
   */
   public synchronized boolean femaleEnters() throws InterruptedException {
       boolean femaleEntered = false;
       STATE state = getState();
       if (state == STATE.Empty) {
           femalesInside++;
           if (femalesWaiting != 0)
               femalesWaiting--;
           femaleEntered = true;
           setState(STATE.WomenPresent);
       } else if (state == STATE.WomenPresent) {
           femalesInside++;
           if (femalesWaiting != 0)
               femalesWaiting--;
           femaleEntered = true;
       } else {
           femalesWaiting++;
           int waitInterval = (int) (Math.random() * (10 - 4) + 4);
           // wait(waitInterval);
           Thread.sleep(waitInterval * 1000);
       }
       displayLoungeStatus();
       notifyAll();
       return femaleEntered;
   }

   /**
   * maleExits method
   *
   * @return
   */
   public synchronized void maleExits() {
       malesInside--;
       if (malesInside == 0) {
           setState(STATE.Empty);
       }
       notifyAll();
       displayLoungeStatus();
   }

   /**
   * femaleExits method
   */
   public synchronized void femaleExits() {
       femalesInside--;
       if (femalesInside == 0) {
           setState(STATE.Empty);
       }
       notifyAll();
       displayLoungeStatus();
   }

   /**
   * display lounge status
   */
   public synchronized void displayLoungeStatus() {
       String state = "";
       STATE name = getState();
       if (name == STATE.Empty)
           state = "Empty";
       else if (name == STATE.MenPresent)
           state = "Men Present";
       else if (name == STATE.WomenPresent)
           state = "Women Present";

       System.out.println("Lounge status:" + state);
       System.out.println("Men inside:" + malesInside);
       System.out.println("Men waiting:" + malesWaiting);
       System.out.println("Women inside:" + femalesInside);
       System.out.println("Women waiting:" + femalesWaiting);
   }
}

-------------------------------

MaleThread class: MaleThread.java

-------------------------------

package unisexlounge;

/**
* MaleThread class
*
*/
public class MaleThread implements Runnable {

   USL usl; // USL instance variable

   /**
   * constructor
   */
   public MaleThread(USL usl) {
       // TODO Auto-generated constructor stub
       this.usl = usl;
   }

   /*
   * (non-Javadoc)
   *
   * @see java.lang.Runnable#run()
   */
   @Override
   public void run() {
       // TODO Auto-generated method stub
       for (int i = 1; i <= 10; i++) {
           int interval = (int) (Math.random() * (10 - 4) + 4);
           try {
               Thread.sleep(interval * 1000);
               boolean result = usl.maleEnters();
               if (result) {
                   int waitInterval = (int) (Math.random() * (5 - 2) + 2);
                   // wait(waitInterval);
                   Thread.sleep(waitInterval * 1000);
                   usl.maleExits();
                   // notifyAll();
               }
           } catch (InterruptedException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
           }
       }
   }

}

---------------------------------------

FemaleThread class: FemaleThread.java

--------------------------------------

package unisexlounge;

/**
* FemaleThread class
*
*/
public class FemaleThread implements Runnable {

   USL usl; // USL instance

   /**
   * constructor
   */
   public FemaleThread(USL usl) {
       // TODO Auto-generated constructor stub
       this.usl = usl;
   }

   /*
   * (non-Javadoc)
   *
   * @see java.lang.Runnable#run()
   */
   @Override
   public void run() {
       // TODO Auto-generated method stub
       for (int i = 1; i <= 10; i++) {
           int interval = (int) (Math.random() * (10 - 4) + 4);
           try {
               Thread.sleep(interval * 1000);
               boolean result = usl.femaleEnters();
               if (result) {
                   int waitInterval = (int) (Math.random() * (5 - 2) + 2);
                   // wait(waitInterval*1000);
                   Thread.sleep(waitInterval * 1000);
                   usl.femaleExits();
                   // notifyAll();
               }
           } catch (InterruptedException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
           }
       }

   }
}

-------------------------------

USLDemo class: USLDemo.java

---------------------------

package unisexlounge;

/**
* USLDemo class
*
*/
public class USLDemo {

   /**
   * @param args
   */
   public static void main(String[] args) {
       // TODO Auto-generated method stub
       //USL object
       USL usl=new USL();
      
       //MaleThread objects
       MaleThread maleThread1=new MaleThread(usl);
       Thread thread1=new Thread(maleThread1);
       MaleThread maleThread2=new MaleThread(usl);
       Thread thread2=new Thread(maleThread2);
       MaleThread maleThread3=new MaleThread(usl);
       Thread thread3=new Thread(maleThread3);
       MaleThread maleThread4=new MaleThread(usl);
       Thread thread4=new Thread(maleThread4);
       MaleThread maleThread5=new MaleThread(usl);
       Thread thread5=new Thread(maleThread5);
      
       //FemaleThread objects
       FemaleThread femaleThread1=new FemaleThread(usl);
       Thread thread6=new Thread(femaleThread1);
       FemaleThread femaleThread2=new FemaleThread(usl);
       Thread thread7=new Thread(femaleThread2);
       FemaleThread femaleThread3=new FemaleThread(usl);
       Thread thread8=new Thread(femaleThread3);
       FemaleThread femaleThread4=new FemaleThread(usl);
       Thread thread9=new Thread(femaleThread4);
       FemaleThread femaleThread5=new FemaleThread(usl);
       Thread thread10=new Thread(femaleThread5);
      
       //start threads
       thread1.start();
       thread2.start();
       thread3.start();
       thread4.start();
       thread5.start();
       thread6.start();
       thread7.start();
       thread8.start();
       thread9.start();
       thread10.start();      
   }

}


Related Solutions

I need to write a java program (in eclipse) that will read my text file and...
I need to write a java program (in eclipse) that will read my text file and replace specific placeholders with information provided in a second text file. For this assignment I am given a text file and I must replace <N>, <A>, <G>, with the information in the second file. For example the information can be John 22 male, and the template will then be modified and saved into a new file or files (because there will be multiple entries...
Please I need this to be done in Java, can I have it answered by anonymous...
Please I need this to be done in Java, can I have it answered by anonymous who answered my last question regarding java? Thank you You will need to implement a specific algorithm implementation to match the class definition AND implement a unit test using JUnit that conforms the specific naming convention. Algorithm: Inputs: integers m and n , assumes m and n are >= 1 Order is not important for this algorithm Local variables integers: remainder Initialize: No initialization...
Hello I need this assignment with citations and biography in APA style as soon as possible...
Hello I need this assignment with citations and biography in APA style as soon as possible 1. It has been found that when health care workers (physicians and nurses) do not practice healthy lifestyle behaviours, this has a negative impact on health promotion as they are less likely to encourage patients to practice healthy behavious. Locate any two validated instruments for measuring habits and personal attitudes of health care workers towards healthy lifestyle behaviours (eg not smoking, eating low risk...
20.1: Checking on the Drought [(JAVA, ECLIPSE), Please keep the program as short as possible] The...
20.1: Checking on the Drought [(JAVA, ECLIPSE), Please keep the program as short as possible] The California drought is a topic that is weighing heavily on the minds of many people in this state. With all the rain we have gotten this year, we are all hoping the drought is over Let's examine some rainfall data for Silicon Valley to get a sense of how this year's rainfall compares to the average rainfall. For this assignment, you will be practicing...
Hello i need someone to implement in JAVA a radix sort algorithm forsorting strings in ascending...
Hello i need someone to implement in JAVA a radix sort algorithm forsorting strings in ascending order. The input to your algorithm should be a (multi)set S = [S1, S2, . . . , Sn] of strings each of which is of length m over the English alphabet [A…Z, a…z]. The output should be the set sorted in ascending lexicographical order. Number of strings is >= 100 and number of characters >= 50 i need the answer fast please
I need this done in JAVA. Define a class named Cash. The class contains the following...
I need this done in JAVA. Define a class named Cash. The class contains the following public elements: A Double stored property that contains the amount of money (dollars and cents) described by an object of the class. A read-only, computed property. It calculates and returns the minimum number of U.S. bills and coins that add up to the amount in the stored property.  The return value is an Int array of length 9 that contains (beginning with index 0 of...
For this coding exercise, you need to create a new Java project in Eclipse and finish...
For this coding exercise, you need to create a new Java project in Eclipse and finish all the coding in Eclipse. Run and debug your Eclipse project to make sure it works. Then you can just copy and paste the java source code of each file from Eclipse into the answer area of the corresponding box below. The boxes will expand once you paste your code into them, so don’t worry about how it looks J All data members are...
This is Java class working on the eclipse. I include some of the codes just so...
This is Java class working on the eclipse. I include some of the codes just so you know what needed. create and work with interfaces you'll create the DepartmentConstants interface presented. In addition, you'll implement an interface named Displayable that's similar to the Printable interface Create the interfaces 1- Import the project named ch12-ex1_DisplayableTest and review the codes package murach.test; public interface Displayable {     String getDisplayText(); } 2 . Note that this code includes an interface named Displayable that...
Hello I need some assistance with these questions I need not so long answers but not...
Hello I need some assistance with these questions I need not so long answers but not too short please Give some examples of How much decisions. What are the implicit costs of having an Airbnb in your neighborhood? What is marginal analysis? What is marginal cost? Under what conditions do marginal costs increase?
Hello, I need to develop a presentation on the International Trade Theory. I need at least...
Hello, I need to develop a presentation on the International Trade Theory. I need at least information for 3 slides and a conclusion. Thanks!
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT