Write a multithreaded Java program that uses semaphores to control access to a one-lane bridge. One thread should simulate eastbound vehicles and another thread should simulate westbound vehicles. The vehicles do not have a reverse gear, so the bridge would become deadlocked if both an eastbound vehicle and a westbound vehicle were allowed to drive onto the bridge at the same time. Therefore, mutual exclusion must be enforced. Your solution should avoid both deadlock and starvation (e.g. the bridge being monopolized by westbound vehicles while the eastbound vehicles never get to cross). The time interval between the successive arrival of vehicles at each direction should be a random interval (sleep) between 0 and 10 seconds. Vehicles traveling in either direction should wait (sleep) for some random amount of time between 0 and 5 seconds, then attempt to cross. Once a vehicle is on the bridge, it should sleep for some random amount of time between 0 and 5 seconds to simulate how long it takes to drive across the bridge.

Output a message when each vehicle is waiting to cross the bridge, a message when each vehicle is crossing the bridge, and another message when that vehicle has completed crossing the bridge. Simulate several vehicles traveling in each direction.

Your solution must have two public classes called EastboundThread and WestboundThread that extends Thread. These classes will be used to simulate eastbound and westbound vehicles. You must also have a public class called Vehicle that extends Thread. This class is used to simulate several vehicles traveling in each direction. You need to define a public class called Bridge that will be accessed by all vehicles. Your static void main( ... ) method must be in a class called OneLaneBridge Tester. In the Bridge class, you need to define a method called reportThread that creates a single thread. This thread must start at the time of creation the bridge object and should display the number of vehicles crossed the bridge from each direction every 30 seconds. The below figure (presented in the lecture) describes the problem of crossing a one-line bridge. You may use one semaphore to control the access of the bridge as shown in the figure. see image.

Output for sample for part I:

Please note that your output results might be different. see image.

Academic Honesty!
It is not our intention to break the school's academic policy. Posted solutions are meant to be used as a reference and should not be submitted as is. We are not held liable for any misuse of the solutions. Please see the frequently asked questions page for further questions and inquiries.
Kindly complete the form. Please provide a valid email address and we will get back to you within 24 hours. Payment is through PayPal, Buy me a Coffee or Cryptocurrency. We are a nonprofit organization however we need funds to keep this organization operating and to be able to complete our research and development projects.