参见英文答案 > Is this starvation? 2个
在我们的大学课程中,我们学习了Threads并使用“Busy Waiting”方法作为在TrafficLight等待的汽车的示例.为此,我们构建了三个类:
> TrafficLight(实现Runnable)
>汽车(实现Runnable)
>主要
在我们的Main类中,我们启动两个Thread,一个是Car,另一个是TrafficLight. Car具有布尔属性hasToWait.这个类中的run()方法的工作方式是,只要hasToWait == true,它就可以通过while循环工作.要更改此设置,我们在Car类中使用notifyCar()方法,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();
}
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();
}
}
问题出在哪儿?为什么它适用于我的教授而不是我的电脑?我使用JRE 1.7在Eclipse Juno中获得了1:1的代码
解决方法:
除了this other answer中所说的所有内容(只需用你的hasToWait代替完成该答案),代码在添加println时开始工作的原因如下:
> println是一种同步方法;
>你在两个线程中调用它;
>这会在两个线程之间创建一个先发生的关系;
>因此,对子线程可以看到对布尔标志的写入.
你可以说它开始大多是偶然的工作:你正在捎带println中正在进行的同步.
标签:java,eclipse,multithreading,busy-waiting
来源: https://codeday.me/bug/20190624/1280401.html