Java, multiple threads with only one executing at a time
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...
M开发者_开发知识库y 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 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?
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
}
}
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
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.
精彩评论