gpt4 book ai didi

java - 如何在 Java 中访问可运行对象中的变量

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:15:15 26 4
gpt4 key购买 nike

我要模拟交通信号灯系统。我创建了扩展 JFrame 并实现 Runnable 的 Road 类。

在 run() 方法中,我添加了增加每辆汽车的 Y 位置的逻辑,它现在正在模拟汽车的运动。但是现在我需要在移动汽车之前检查交通灯的状态。

这是我的 TrafficLight 类,

import java.util.Random;

public class TrafficLight implements Runnable {

volatile boolean stop;

public TrafficLight(boolean stop) {
this.stop = stop;
}

@Override
public void run() {
Random randomGenerator = new Random();
while (true) {
if (stop) {
stop = false; //change current status
} else {
stop = true; //change current status
}
try {
Thread.sleep(2000 + randomGenerator.nextInt(2000));
} catch (Exception ex) {
System.out.println("error");
}
}
}
}

有什么方法可以从我的 Road Class 中检查这个 volatile 变量 stop

如果不是,请建议我另一种解决方案。

谢谢。

最佳答案

为停止实现访问器。

public class TrafficLight implements Runnable {

volatile boolean stop;

// Irrelevant code

public boolean isStop() {
return stop;
}
}

Road 类构造函数上接收 TrafficLight 并使用它来访问 stop 变量

public class Road implements Runnable {

private TrafficLight trafficLight;

public Road (TrafficLight trafficLight) {
this.trafficLight = trafficLight;
}

@Override
public void run() {
// Irrelevant code
if(trafficLight.isStop()) {
// do something
}
}
}

关于java - 如何在 Java 中访问可运行对象中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8712251/

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