gpt4 book ai didi

java多线程: traffic intersection system

转载 作者:行者123 更新时间:2023-11-30 07:26:52 27 4
gpt4 key购买 nike

我试图通过2个线程在java中使用多线程,其中一个线程代表一辆汽车以单向行驶通过十字路口,另一个线程代表另一辆汽车等待通过十字路口。我的问题是 car2 打印“car2 is waiting to cross”的次数比应有的次数多(它应该只打印 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 米”相同的次数,但每次都是随机的?

最佳答案

调用car1的incrementDistance()方法后,car2的race()方法不必只执行一次。该方法有可能被多次调用。欢迎来到不规则的日程安排世界。

您应该做的是使用条件通知 car2 car1 已调用incrementDistance(),并且 car2 应在其 race() 方法中等待此条件。这将确保 car2 打印预期的输出..

关于java多线程: traffic intersection system,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36710555/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com