Biblioteca Java - Rev 27
Subversion Repositories:
package ex3_roadtraffic;
/*
A bridge over a river contains only a single lane, but cars enter from both direction.
Consequently, some kind of synchronisation is needed to keep cars from colliding.
To illustrate the problem we provide you with a malfunctioning solution, in which no synchronisation is performed.
Your task is to add synchronisation to the cars.
All you need to know is that cars going from left to right call the method controller.enterLeft() when they
approach the bridge (to ask for permission) and call the method controller.leaveRight() when they leave.
Cars in the other direction call enterRight and leaveLeft instead. Here, controller is an instance of the
class TrafficController, which is responsible for synchronisation. As you can see, the supplied class has
empty implementations of all four methods. Your task is to change this class into a monitor that coordinates
cars so that they do not collide.
*/
public class Main {
private static void nap(int ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {}
}
public static void main(String[] a) {
final CarWindow win = new CarWindow();
win.pack();
win.setVisible(true);
new Thread(new Runnable() {
public void run() {
while (true) {
nap(25);
win.repaint();
}
}
}).start();
}
}
/*
A bridge over a river contains only a single lane, but cars enter from both direction.
Consequently, some kind of synchronisation is needed to keep cars from colliding.
To illustrate the problem we provide you with a malfunctioning solution, in which no synchronisation is performed.
Your task is to add synchronisation to the cars.
All you need to know is that cars going from left to right call the method controller.enterLeft() when they
approach the bridge (to ask for permission) and call the method controller.leaveRight() when they leave.
Cars in the other direction call enterRight and leaveLeft instead. Here, controller is an instance of the
class TrafficController, which is responsible for synchronisation. As you can see, the supplied class has
empty implementations of all four methods. Your task is to change this class into a monitor that coordinates
cars so that they do not collide.
*/
public class Main {
private static void nap(int ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {}
}
public static void main(String[] a) {
final CarWindow win = new CarWindow();
win.pack();
win.setVisible(true);
new Thread(new Runnable() {
public void run() {
while (true) {
nap(25);
win.repaint();
}
}
}).start();
}
}