gpt4 book ai didi

java - 如何在此嵌入式程序中不使用全局变量?

转载 作者:行者123 更新时间:2023-12-02 09:10:05 27 4
gpt4 key购买 nike

我相信我们公司有一个边缘情况,这阻止我进入“从不使用全局变量阵营”。

我们需要编写一个在我们的盒子中运行的嵌入式应用程序,从医院的设备中提取医疗数据。

即使医疗设备被拔掉、网络消失或者我们的盒子设置发生变化,它也应该无限运行。设置是从 .txt 文件中读取的,可以在运行时轻松更改该文件。

这就是为什么单例模式对我来说没有用。所以我们时不时地返回(读取 1000 个数据后)并读取如下设置:

public static SettingForIncubator settings;

public static void main(String[] args) {
while(true){
settings = getSettings(args);

int counter=0;

while(medicalDeviceIsGivingData && counter < 1000){
byte[] data = readData(); //using settings

//a lot of of other functions that use settings.

counter++;
}
Thread.Sleep(100); //against overheating and CPU usage.
}
public byte[] readData(){
//read Data from the port described in settings variable
}
}

还有其他方法可以设计程序吗?

最佳答案

我不太清楚你的意思,但我认为这段代码会对你有所帮助:

class SettingsForIncubator {
}

public class MedicalProcessor {

protected volatile boolean active;
protected volatile boolean medicalDeviceIsGivingData;

public void start(String[] args) throws Exception {
this.active = true;
Thread thread = new Thread(() -> loop(args));
thread.start();
}

protected void loop(String[] args) {
System.out.println("start");
while(active) {
SettingsForIncubator settings = getSettings(args);
int counter=0;

while(medicalDeviceIsGivingData && counter < 1000){
byte[] data = readData(settings); //using settings

//a lot of of other functions that use settings.

counter++;
}
try {
Thread.sleep(100); //against overheating and CPU usage.
}
catch (Exception e) {
break;
}
}
}

protected byte[] readData(SettingsForIncubator settings) {
// logic read data
return null;
}

protected SettingsForIncubator getSettings(String[] args) {
// logic to get settings
return null;
}

public void stop() {
this.active = false;
}

public static void main(String[] args) throws Exception {
MedicalProcessor processor = new MedicalProcessor();
processor.start(args);
}

}

关于java - 如何在此嵌入式程序中不使用全局变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59490348/

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