Thread classes in JAVA (emergency)
documents--ECET490_W1_Lab_Threads_and_Synchronization_Program.docx
ECET-490
Threads and Synchronization
Whenever we have multiple entities working together to get something done, we have the problem of synchronization between the entities. Processes working together, or threads in one or many processes working together, need tools to protect critical sections and to signal one another when important events occur. Java provides thread and synchronization mechanisms which programmers can use to coordinate their activities. The following problem requires that many threads coordinate their activities to assure that the program runs correctly.
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.
Turn in your output sample and source code, as well as your signed-off coversheet.
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.
ECET 490 week 1 dsetliff.pptx
ECET 490
Week 1 Lab Presentation
Suggestions and Helpful Hints
Professor Dottie Setliff
First things first – Install JDK first
Make sure you install for your HW/OS
32 bit vs 64 bit is usually not an issue but check your system first
You must have administrative rights!
Remember trick: right-click and select run-as-administrator if needed
Install JRE also
Install Eclipse IDE after JDK installation
Download anywhere really
Install by unzipping to top level directory- C:\eclipse
Strong Suggestion:
make a shortcut icon to access Eclipse from desktop
Create a workspace folder at top level directory
Create a new workspace for each week, or just use one workspace for the entire coure
You can organize how you want
Remembering how to use Eclipse (or rather Eclipse IDE)
To run eclipse IDE: double click the shortcut and click on ‘run’ option
Browse to your workspace, then click OK
Starting up Eclipse IDE
You don’t have a folder yet?
go ahead a make one!
Make a folder called workspace
Click Browse and browse to workspace
Click Make New folder, Click OK
Name it
Click OK until Eclipse IDE starts
3 times I think
Here I named it Week1presentation
Empty Workspace
Go through Tutorials
When ready to start your lab file
File->New->Java Project (You may need to choose other to see Java Project option)
Creating a Java project
Fill in project name
Week1Lab here
Click Finish
Click ‘yes’ to open
correct Java
perspective
Click below ‘File’
Expand Week1Lab
To add packages, highlight project name and do a new->package
Type in package name in the popup window
For example: you could type in week1Lab and click ‘Finish’ to now see…..
Projects made of packages with classes
Click on src, do a new->class to add classes to your package
Ready to write code implementing the methods of the class MaleThread
Now let’s look at what you have to build in this lab….
What is Lab 1 all about?
Learning about
Threads
Synchronizing threads
The politically correct bathroom is a common assigned problem
Yes, variations exist and are searchable
How to start – Read the Assignment of course
This is not all that easy so start early
Basically, just do each sentence
Okay, but what does it do?
The bathroom can only hold males or females. Not both.
If it is empty or same gender, then go in
You have to decide if you want to cap the number of people in the bathroom or not but the cap must be greater than 1!
You have to allow more than 1 person of same gender in the bathroom
If you do decide to cap, then you must describe the cap in your writeup
You do have to decide what you want to output each time someone tries to visit the bathroom, or leaves the bathroom
Otherwise, you wait (well, your code waits …)
Only need 4 class
Create the 4 classes as
named in assignment
The Person class shown
here is extraneous
(you don’t need it)
Used default package
This is tacky, but….
Now let’s look at each !
MaleThread Class get FemaleThread by changing all ‘Male’ to ‘Female’
MaleThread extends Thread
But what does MaleThread need to do?
loop 10 times
each iteration
is an attempt to go
to the bathroom
Read instructions carefull! Need to wait before enter bathroom between 4 and 10 seconds!
Need to wait in bathroom between 2 and 5 seconds (on top of any waiting caused by bathroom management)
Java method calls you need to know
Thread.sleep
http:// docs.oracle.com/javase/tutorial/essential/concurrency/sleep.html
Math.random
http :// javarevisited.blogspot.com/2013/05/how-to-generate-random-numbers-in-java-between-range.html
But remember:
thread calls need to be surrounded by a try {} and all exceptions have to be caught!
Will be tested on!
Bathroom class
Constructor has to initialize !
Use synchronized methods!
manEnter, manExit, womanEnter, womanExit
Be sure you understand why
Let’s look at manEnter in some detail in psuedo code
You can figure out womanEnter and womanExit
manEnter
This is pseudo code and meant to get idea across of the rest of the code in this method
try {
// if bathroominuse and numberWomeninbathroom > 0 then increment men waiting and wait()!
} finally {
// the bathroom is available and empty !!!! No women are in there
// bathroominuse is now true
// numberMeninbathroom increments
// if numberMenwaiting > 0 then decrement
// I suggest using system.out.print and system.out.println
// but print first what changed …in this case…. a man Entered
// plus values of all the variables. This will help your debugging
}
What does wait() do? Causes thread to pause until monitor uses notify to wake it up (we’ll be using notifyAll !)
http:// stackoverflow.com/questions/1036754/difference-between-wait-and-sleep
Corresponding manExit
// in this case you want to leave the bathroom - more pseudo code!
try { // this will wait until bathroom can be left (which always happens)
if numbermenInBathroom > 0 then decrement numbermeninBathroom
if no more numbermeninBathrom { // then bathroom is empty!
bathroominuse is false
notifyAll();
}
} finally {
// use System.out.print and System.out.println to print out
// all state info just like you did in manEnter, but this time
// the status change is man Exited the bathroom!
}
What is notifyAll()? This unblocks all waiting threads!
runBathroom
Implements the ‘Main Test Program’ section of Lab Assignment. It runs the bathroom!
Start things off by setting up a bathroom
Use ArrayList construct to hold the threads
Use a for loop to generate the needed 10 threads
How to create a new thread and add threads to ArrayList? This will add in a male and then a female thread
More runBathroom
Then…
Start all 10 threads !
ArrayList is a nifty way to organize and use the threads
After start them all up, just wait for them all to end…
To do that, use same type of for loop as used to start, but this time inside loop have ….
try { //waits for all threads to complete
Use threads join() method
}
catch exceptions !!
What about Lab results?
Use ‘Run’ to start your program…
Output all status changes and state variables whenever anyone enters or exits bathroom to eclipse console
Sample Output from console at bottom of eclipse IDE screen….
Woman Entered. Men in 0 Men Waiting is 0
Women in 1 Women Waiting is 0
Woman Entered. Men in 0 Men Waiting is 2
Women in 2 Women Waiting is 0
2 men came up to bathroom while woman was in bathroom but had to wait. They will wait until bathroom is empty.
Notifyall() is key!
It is not necessary to worry about starvation issues
Some interesting items:
Reduce the amount of time inside bathroom and watch the number of people waiting decrease.
Decrease the time BETWEEN needing to go the bathroom and what happens?
Good Luck!
You are spinning back up in Java experience
Use this as a guide but remember it is only a guide
Idea here is to help you successfully complete this first lab!
Turn in
Source code files
Status report Output
Discuss how the program works, include a paragraph of what happens when increase or decrease the required ‘wait’ times!!!!
You can do it!
Archive created by free jZip.url
[InternetShortcut] URL=http://www.jzip.com/archive_link