During our lessons at the university, we learned about Threads
and used the "Busy Waiting" method for an example Car
, waiting at a TrafficLight
. For this task, we create three classes:
TrafficLight (implements Runnable)
Car (implements Runnable)
Main
In our class, Main
we run two Thread
s, one of Car
and one of TrafficLight
. Car
has a boolean attribute hasToWait
. The method run()
in this class works so that it works through the loop while
, for now hasToWait == true
. To change this, we have a method notifyCar()
in the class Car
that is used TrafficLight
. Method run()
to TrafficLight
pass through Thread.sleep()
to simulate a certain waiting time.
Everything works fine in my Prof, but in the end I have serious problems with it. While the loop while
in the class is Car
empty. When I insert System.out.println()
- which is not empty, it works. But if Syso is empty, the result does not display the method text Run
. It also works when Thread.sleep()
in TrafficLight
equal 0
. How does it work with an empty loop while
.
Here is my code:
Car.java:
package trafficlight;
public class Car implements Runnable {
private boolean hasToWait = true;
public void run() {
this.crossTrafficLight();
}
public void crossTrafficLight() {
while(hasToWait){ for(int i = 0; i<20; i++){System.out.println("123");}}
System.out.println("Auto fährt über Ampel");
}
public void notifyCar() {
this.hasToWait = false;
System.out.println("Test");
}
}
TrafficLight.java:
package trafficlight;
public class TrafficLight implements Runnable {
private Car car;
public TrafficLight(Car car) {
this.car = car;
}
@Override
public void run() {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.car.notifyCar();
}
}
Main.java:
package trafficlight;
public class Main {
public static void main(String[] args){
Car car = new Car();
TrafficLight tl = new TrafficLight(car);
new Thread(car).start();
new Thread(tl).start();
}
}
Where is the problem? Why does this work for my professors, but not on my computer? I got the code 1: 1 in my Eclipse Juno usingJRE 1.7
source
share