首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我怎么能不在这个嵌入式程序中使用全局变量呢?

我怎么能不在这个嵌入式程序中使用全局变量呢?
EN

Stack Overflow用户
提问于 2019-12-26 23:25:11
回答 1查看 55关注 0票数 0

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

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

这应该是无限运行的,即使当医疗设备被关闭,网络消失,或我们的盒子的设置发生变化。设置是从.txt文件中读取的,该文件可以在运行时进行更改,最好没有问题。

这就是单例模式对我没有用处的原因。因此,我们会不时地返回(在读取1000个数据之后),并像这样读取设置:

代码语言:javascript
复制
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
    }
}

还有没有其他方法可以设计这个程序?

EN

回答 1

Stack Overflow用户

发布于 2019-12-27 00:48:40

我不知道你到底是什么意思,但我认为这段代码会对你有所帮助:

代码语言:javascript
复制
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);
    }

}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59490348

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档