Tag: 忙等待

线程:忙等待 – 空循环

在我们的大学课程中,我们学习了Threads并使用“Busy Waiting”方法作为在TrafficLight等待的Car的TrafficLight 。 为此,我们构建了三个类: TrafficLight (implements Runnable) Car (implements Runnable) Main 在我们的Main类中,我们启动两个Thread ,一个是Car ,另一个是TrafficLight 。 Car具有布尔属性hasToWait 。 这个类中的run()方法的工作方式是,只要hasToWait == true ,它就可以通过while循环工作。 要更改此设置,我们在notifyCar()类中使用notifyCar()方法, TrafficLight使用该TrafficLight 。 TrafficLight的run()方法运行Thread.sleep()来模拟一定的等待时间。 我教授的一切都很好,但最终我遇到了严重的问题。 只要Car类中的while循环为空。 当我输入System.out.println() – 它不是空的时,它可以工作。 但是如果Syso为空,则结果是不显示Run of Run方法。 当TrafficLight的Thread.sleep()为0时,它也正常工作。 比它使用空的while循环。 这是我的代码: Car.java: package trafficlight; public class Car implements Runnable { private boolean hasToWait = true; public void run() { this.crossTrafficLight(); […]