4

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?

The Unfun Cat
  • 29,987
  • 31
  • 114
  • 156
SomeoneRandom
  • 264
  • 1
  • 7
  • 19

4 Answers4

5

You probably want to read up on wait and notify. 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 call notify. When a person object returns from wait, it is their turn to cross (as I understand your problem.) When the person crosses, the bridge object would call notify again.

Make sure you synchronize correctly. The tutorials should help.

Read this question as well: How to use wait and notify in Java?

Community
  • 1
  • 1
Starkey
  • 9,673
  • 6
  • 31
  • 51
2

Lock an object like this:

// Bridge.java

public class Bridge {
private Object _mutex = new Object();

    public void cross(Person p)
        synchronized(_mutex) { 
             // code goes here
        }     
    }
}

That is one, probably the easiest, method..

EDIT:

even easier:

public class Bridge {
    public synchronized void cross(Person p)
    {
        // code goes here
    }
}
Richard J. Ross III
  • 55,009
  • 24
  • 135
  • 201
  • Using a synchronized method seems to be the most elegant Java solution possible. The asker can see ["Synchronized Methods"](http://download.oracle.com/javase/tutorial/essential/concurrency/syncmeth.html) for a description of what all it does. It won't teach anyone much about semaphores or mutexes/conditions, but it's the instructor's own fault for selecting something as high-level as Java to teach something as low-level as synchronizing access between multiple threads. – Jeremy W. Sherman Oct 18 '10 at 23:10
0

I believe what the assignment is asking you to do is to use (or implement) a mutex for access to the shared resource, aka the bridge. http://en.wikipedia.org/wiki/Mutex

kkress
  • 777
  • 5
  • 6
0

Try java.util.concurrent:

http://download.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/Executors.html#newSingleThreadExecutor%28%29

This class wil produce an ExecutorService, where you can submit yout "Persons". And the Jobes are queued, one Person will cross at time.

Christian Kuetbach
  • 15,850
  • 5
  • 43
  • 79