Objective
- To understand thread synchronization problems (safety)
- To use the java framework for concurrency and understand the basic mechanisms for thread synchronization provided by it
- To use synchronized methods to solve problems
Preparation
- Download the code for the too much milk problem from moodle
- Import the project into IntelliJ (or your framework of preference) and run
- Eventually, you will run into the Too Much Milk! Problem
- Read the synchronization section from the Java Tutorial https://docs.oracle.com/javase/tutorial/essential/concurrency/sync.html
Tasks
- To solve the too much milk problem you need to use the keyword synchronized. Identify whether it is the method (https://docs.oracle.com/javase/tutorial/essential/concurrency/syncmeth.html ) or an object (https://docs.oracle.com/javase/tutorial/essential/concurrency/locksync.html) that needs to be synchronized on. When running the code, you should see that the execution continues without facing the too much milk problem.
- Write the code to solve the following problem:
You have been hired to coordinate people trying to cross a river. There is only a single boat, capable of holding at most three people. The boat will sink if more than three people board it at a time. Each person is modeled as a separate thread, executing the function below:
Person(int location)
// location is either 0 or 1;
// 0 = left bank, 1 = right bank of the river
{
ArriveAtBoat(location); BoardBoatAndCrossRiver(location); GetOffOfBoat(location);
}
Synchronization is to be done in the two methods ArriveAtBoat and GetOffOfBoat. Provide the code for ArriveAtBoat and GetOffOfBoat. ArriveAtBoat must not return until it safe for the person to cross the river in the given direction (it must guarantee that the boat will not sink, and that no one will step off the pier into the river when the boat is on the opposite bank). GetOffOfBoat is called to indicate that the caller has finished crossing the river; it can take steps to let other people cross the
river.
BoardBoatAndCrossRiver returns the location where the person gets off boat and is passed to the getOffOfBoat.
Simulate 20 persons at location 1 trying to cross to location 0 at the same time and show that they are safely crossed. Use print statements to show the simulation steps.
Further reading
If you want to learn about thread programming in C/C++ (POSIX Threads) https://concordiauniversity.on.worldcat.org/oclc/137284099





