Beruflich Dokumente
Kultur Dokumente
Lets assume, we have a town with a main road around the city. 7 traffic lights are installed to regularize the traffic. 20 cars are simultaneously on this city circle. Simulate this situation using the following framework by extending the program on the yellow marked positions. class TrafficLight { private boolean red; public TrafficLight() { } public synchronized void pass() { // if red, cars have to wait } public synchronized void switchRed() { } public synchronized void switchGreen() { // if green, notify that all cars can start driving } } class Car extends Thread { private TrafficLight[] trafficLights; private int pos; // position of car (before traffic light pos public Car(String name, TrafficLight[] trafficLights) { } private synchronized void goAhead() { pos++; } public synchronized int position() { } public void run() { while(true) { try { sleep((int)(Math.random() * 500)); // driving around for some time } catch(InterruptedException e) {} trafficLights[pos].pass(); // wait before a traffic light goAhead(); // go on driving to next traffic light } }
1/3
Thread.sleep(1000); } catch(InterruptedException e) {
// show situation at each traffic light
System.out.println("==================="); for(int j = 0; j < trafficLights.length; j++) { String prefix; if(j == i || j == i+1) prefix = "->"; else prefix = " "; System.out.print(prefix + "in front of light " + j + ":"); for(int k = 0; k < Cars.length; k++) { // cars at traffic light j if(Cars[k].position() == j) System.out.print(" " + k); } System.out.println(); } System.out.println("==================="); try { // let us observe the situation Thread.sleep(5000); } catch(InterruptedException e) {} trafficLights[i].switchGreen(); // switch light i to green if(i+1 < trafficLights.length) trafficLights[i+1].switchGreen(); // switch light i+1 to green try { // wait until swiching to red Thread.sleep((int)(Math.random() * 500)); } catch(InterruptedException e) {} trafficLights[i].switchRed(; // switch light i to red if(i+1 < trafficLights.length) trafficLights[i+1].switchRed(); // switch light i+1 to red
2/3
3/3