I am working on an assignment and have to create two classes, one represents a person, and the other representing a bridge. Only one person can be “crossing” the bridge at any one time, but there could be people waiting to cross
I easily implemented this with multi-threading allowing for multiple people to cross at once, but I am having issues when changing it to allow only one thread to run…
My main problem is the class design they want, I have to begin the threads within the person class, but the bridge class needs to be able to wait and notify them to start/stop
Any ideas how I can do this?
You probably want to read up on
waitandnotify. There are tutorials with a google search.But after you understand them a bit, you want to have the person objects call
wait. Then you want the bridge object to callnotify. When a person object returns fromwait, it is their turn to cross (as I understand your problem.) When the person crosses, the bridge object would callnotifyagain.Make sure you
synchronizecorrectly. The tutorials should help.Read this question as well: How to use wait and notify in Java?