【问题标题】:sleep() over 1000 milis blocks Thread forever - androidsleep() 超过 1000 milis 永远阻塞线程 - android
【发布时间】:2021-07-07 16:23:28
【问题描述】:

我正在接收来自 HC-05 的实时数据,只是从 0 到 1023 的数字。 SleepDuration 变量用于从 HC-05 获取数据之间的睡眠持续时间,用户可以在 1 秒到 2 秒之间选择,这就是问题所在:

当用户为 SleepDuration 选择 1 秒时,程序运行良好,但当他选择超过 1 秒时,该线程在获得少量数据后永远休眠。

这是我接收数据的代码:

public void run() {
        byte[] buffer = new byte[1024];  // buffer store for the stream

        int bytes; // bytes returned from read()

        // Keep listening to the InputStream until an exception occurs
        while (true) {

            // Read from the InputStream
            try {
                bytes = mmInStream.read(buffer);
                incomingMessage = new String(buffer, 0, bytes);

                try {
                    sleep(SleepDuration);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            } catch (IOException e) {
                Log.e(TAG, "write: Error reading Input Stream. " + e.getMessage());
                break;
            }
        }
    }

【问题讨论】:

  • 当没有更多数据要读取时它会阻塞吗?
  • @FrancescoRe 不,它会无缘无故地阻止
  • 你是在主线程还是在单独的线程中执行代码?
  • 一个单独的线程@FrancescoRe
  • 显示更多关于如何启动线程的代码

标签: java android multithreading bluetooth sleep


【解决方案1】:

如果您被阻止进入指令 mmInStream.read(buffer)

,就会发生这种情况

基本上,当您调用读取时,您会阻止客户端等待一些数据,如果数据没有到达您的代码会永远阻塞在读取中。

【讨论】:

  • 不,数据来了,当我选择 1 秒作为睡眠时间时它工作正常
猜你喜欢
  • 1970-01-01
  • 2022-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-06
  • 1970-01-01
相关资源
最近更新 更多