<分区>
在我们大学的类(class)中,我们学习了Threads
,并使用了“Busy Waiting”方法作为一个Car
在TrafficLight<等待的例子
。对于这个任务,我们构建了三个类:
TrafficLight(实现 Runnable)
Car(实现 Runnable)
主要
在我们的 Main
类中,我们启动了两个 Thread
,一个是 Car
,另一个是 TrafficLight
。 Car
具有 boolean 属性 hasToWait
。此类中的 run()
方法的工作方式是,只要 hasToWait == true
,它就会通过 while
循环工作。为了改变这一点,我们在 Car
类中使用了 notifyCar()
方法,该方法由 TrafficLight
使用。 TrafficLight
中的run()
方法运行一个Thread.sleep()
来模拟一定时间的等待。
在我的教授那里一切正常,但最终我遇到了严重的问题。只要 Car
类中的 while
循环为空。当我输入 System.out.println()
- not 为空时,它起作用了。但是如果Syso 为空,则结果是不显示Run
方法的Text。
当 TrafficLight
中的 Thread.sleep()
为 0
时,它也有效。它适用于空的 while
循环。
这是我的代码:
汽车.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");
}
}
交通灯.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();
}
}
主.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();
}
}
问题出在哪里?为什么它适用于我的教授,但不适用于我的电脑?我使用 JRE 1.7