views:

97

answers:

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?

A: 

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
+2  A: 

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
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
+5  A: 

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: http://stackoverflow.com/questions/886722/how-to-use-wait-and-notify-in-java

Starkey
A: 

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.

ckuetbach
After reading yout post again, I'm not sure, if you can chachge your design, to you this Features.
ckuetbach