Topics: Busy Waiting - Empty While-Loop

During our lessons at the university, we learned about Threadsand 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, Mainwe run two Threads, one of Carand one of TrafficLight. Carhas 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 Carthat is used TrafficLight. Method run()to TrafficLightpass 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 whilein the class is Carempty. 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 TrafficLightequal 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");}} // Busy waiting
        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

+4
source share
2 answers

, ( hasToWait finished ), , , println :

  • println - ;
  • ;
  • ;
  • .

, : println.

+3

- hasToWait. . , .

- .

:

(. ), , 2 ( volatile) - .

, -: , , , , . , JVM . , , .

+1

Source: https://habr.com/ru/post/1523316/


All Articles