线程实现每秒查询设备状态,有变化时执行其他操作

1.写一个线程方法去判断状态值是否改变

    private void waitForDeviceStatus(IntByReference senor_code, IntByReference status_code, String targetHex) {
        Thread statusThread = new Thread(() -> {
            try {
                //在这里调用查看设备状态方法
                OwnershipMainSdk.LIB.HWX_GetDeviceStatus(senor_code, status_code);
                String currentHex = handleResult(status_code.toString());
                //比较获取到的状态是否是某个值,如果不是就继续获取设备状态
                while (!currentHex.equals(targetHex)) {
                    Thread.sleep(1000); // 每秒检查一次设备状态,可以根据实际情况调整
                    OwnershipMainSdk.LIB.HWX_GetDeviceStatus(senor_code, status_code);
                    currentHex = handleResult(status_code.toString());
                }
            } catch (InterruptedException e) {
                throw new BusinessException("获取设备状态失败");
            }
        });
        statusThread.start();

        try {
            statusThread.join(); // 等待statusThread线程执行完成
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

2.在需要时调用上述方法

waitForDeviceStatus(senor_code, status_code, "0");
log.info("获取到设备的状态0;");
posted @ 2024-09-03 14:21  山茶花llia  阅读(5)  评论(0编辑  收藏  举报