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

问题描述 投票:0回答:1

我相信我们公司有一个极端的案例,这使我无法进入“永不使用全局变量阵营”。

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

这应该无限期地运行,即使在关闭医疗设备,网络消失或我们的盒子设置改变的情况下也是如此。设置是从.txt文件读取的,可以在运行时更改它,而最好不要麻烦。

这就是为什么Singleton模式对我没有用。因此,我们不时返回(在读取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
    }
}

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

java while-loop global-variables global static-variables
1个回答
0
投票

我不确定您的意思,但是我认为这段代码可以为您提供帮助:

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);
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.