multithreaded Java program
Write a multithreaded Java program that uses synchronized methods (Section 7.4.1), reentrant locks (Section 7.4.2), or semaphores (Section 7.4.3) to control access to a one- lane bridge. One thread should simulate westbound vehicles and another thread should simulate eastbound vehicles. The vehicles do not have a reverse gear, so the bridge would become deadlocked if both a westbound vehicle and an eastbound vehicle were allowed to drive onto the bridge at the same time. Therefore, mutual exclusion must be enforced on the use of the bridge. 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). Vehicles traveling in either direction should wait (sleep) for some amount of time, then attempt to cross. Once a vehicle is on the bridge, it should sleep for some amount of time to simulate how long it takes to drive across the bridge.
Output a message when each vehicle drives onto the bridge and another message when that vehicle has completed the crossing. Simulate several (at least five) vehicles traveling in each direction.
Per the images below, I have most of the code finished. But for some reason the output is only giving me the threads entering the bridge sequentially and not from both sides. There is an issue with the mutual exclusion that I cannot figure out. Please help.
Trending now
This is a popular solution!
Step by step
Solved in 3 steps