Java, multiple threads with one executable at a time

I am working on a task and have to create two classes, one representing a person and the other a bridge. Only one person can "cross" the bridge at any time, but there may be people waiting for the intersection.

I easily implemented this with multithreading, allowing several people to intersect at once, but I am having trouble changing it, allowing only one thread to run ...

My main problem is the design of the class that they need, I have to start streams inside the person class, but the bridge class must be able to wait and notify them of start / stop

Any ideas how I can do this?

+4
source share
4 answers

You probably want to read on wait and notify . There are google search tutorials.

But after you understand them a little, you want the human objects to call wait . Then you want the bridge object to call notify . When the person object returns with wait , it is their turn to cross (as I understand your problem.) When the person crosses, the bridge object will call notify again.

Make sure you synchronize correctly. Textbooks should help.

Also read this question: How to use wait and notify in Java?

+5
source

Lock this object:

 // Bridge.java public class Bridge { private Object _mutex = new Object(); public void cross(Person p) synchronized(_mutex) { // code goes here } } } 

This is one, perhaps the easiest way.

EDIT:

even simpler:

 public class Bridge { public synchronized void cross(Person p) { // code goes here } } 
+2
source

I believe that the task will ask you to do this, use (or implement) a mutex to access a shared resource, otherwise a bridge. http://en.wikipedia.org/wiki/Mutex

0
source

Try java.util.concurrent:

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

This class will create an ExecutorService where you can send Faces. And workers stand in line, one Man will cross the time.

0
source

All Articles