我试图通过具有2个线程在Java中使用多线程,其中一个线程代表一辆汽车通过十字路口,另一条代表另一辆汽车等待通过十字路口。我的问题是car2打印出“ car2等待穿越”的次数比它应打印的次数多(它应该只打印6次)。我已经尝试过使用同步化功能,但这不起作用。它是一个非常简单的程序,我正尝试制作它来帮助自己了解多线程,如下所示。
public class Drive {
public static Thread car1;
public static Thread car2;
public static void main(String[]args){
Cars cars = new Cars();
car1 = new Thread(cars, "car 1");
car2 = new Thread(cars, "car 2");
car1.start();
car2.start();
}
}
public class Cars implements Runnable{
int distance = 0;
public void increaseDistance(){
distance ++;
}
public void race(){
while(distance <= 5){
if(Thread.currentThread().getName().equals("car 1")){
System.out.println("Distance covered by " + Thread.currentThread().getName() + " is " + distance + " meters");
increaseDistance();
}
if(Thread.currentThread().getName().equals("car 2")){
System.out.println(Thread.currentThread().getName() + " is waiting to cross");
}
}
}
public void run(){
race();
}
}
输出即时消息低于...
car 2 is waiting to cross
car 2 is waiting to cross
car 2 is waiting to cross
car 2 is waiting to cross
car 2 is waiting to cross
Distance covered by car 1 is 0 meters
car 2 is waiting to cross
Distance covered by car 1 is 1 meters
Distance covered by car 1 is 2 meters
Distance covered by car 1 is 3 meters
Distance covered by car 1 is 4 meters
Distance covered by car 1 is 5 meters
car 2 is waiting to cross
它说“汽车2等待穿越”的位置应该打印出与“汽车1所覆盖的距离为x米”相同的时间,但是每次都随机打印吗?
最佳答案
car2的race()方法不必在car1的crementDistance()方法被调用后才执行一次。有可能多次调用此方法。欢迎来到不规则的调度世界。
您应该做的是使用条件来通知car2 car1调用了invokeDistance(),而car2应该在其race()方法中等待此条件。
这将确保car2打印出预期的输出。
关于java - java multithreading:交通路口系统,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36710555/