【问题标题】:How to wait until data is received and fully processed, before sending the next set of data request?如何等到数据被接收并完全处理后,再发送下一组数据请求?
【发布时间】:2015-03-17 12:13:37
【问题描述】:

我找到了一些答案,“等待、通知、同步、线程等”,但不确定如何将其应用到我的代码中。在Trigger() 方法中,我希望它等到dataACK = true 再执行下一个SendCommand

private void ReceiveData(byte[] rData) {
    // ReceiveData() is called when there's data received
    ...
    ...
    ...
    dataACK = true;
}

private void SendCommand(String instruction){

    ...
    ...
    ...
    dataACK = false;
    OutToPort(instruction);             
    // OutToPort() will cause ReceiveData() to execute 
    // when data is received a few ms later
}

private void Trigger(){
    SendCommand("Command1");
    // here it waits until dataACK is set to true

    SendCommand("Command2");
    // here it waits until dataACK is set to true

    SendCommand("Command3");
}

【问题讨论】:

  • 与论坛网站不同,我们不使用“谢谢”、“任何帮助表示赞赏”或Stack Overflow 上的签名。请参阅“Should 'Hi', 'thanks,' taglines, and salutations be removed from posts?。顺便说一句,这是“提前致谢”,而不是“致谢”。
  • 谢谢@John Saunders。还是我不应该感谢你.. ;) 无论如何,有什么想法可以帮助我吗?
  • 如果我有一个想法,如果我想“帮助你”,那么我可以这样做。由于我选择不“帮助你”,你可能会认为我要么不知道,要么不想以这种方式帮助你。我确实帮助你解决了问题,消除了你的问题,让你更有可能得到好的答案,甚至更多你的问题可能会在未来。

标签: java android threadpool wait synchronized


【解决方案1】:

wait() 方法意味着你等到资源没有被锁定。而 notify() 表示你现在要从临界区出来并释放资源。 所以如果你想等到一个数据发送出去,你必须在发送消息之前进入临界区,在发送完所有消息后从临界区出去。 我认为您必须在每次调用 SendCommand("content") 的第一次调用 wait() 并在 SendCommand 方法的末尾调用 notify 函数。

【讨论】:

  • 嗯...我再次阅读了您的代码,我猜您没有使用多线程。您只是依次调用 SendCommand 方法 3 次。那么你不能使用 wait() 和 notify() 因为 wait() 方法会等到另一个线程调用 notify() 方法。
  • 也许你可以在 void SendCommand() 前面使用 'synchronized' 关键字,因为如果你对一个方法使用这个关键字,那么如果该方法被执行,就不能同时执行其他线程.我没试过,所以如果你试了,请告诉我和其他人结果:)
  • 我确实尝试过。它没有帮助。 SendCommand() 不是我等待的,而是 ReceiveData(byte[] rData) 设置标志 dataACK = true;
  • 现在我明白你的意思了。然后您必须在调用 OutToPort 方法并在 ReceiveData 方法的末尾调用 notify() 后等待。如果不想使用wait() 和notify(),可以使用while 语句的busy waiting。这不是推荐的方式,但会更容易。
  • 我无法弄清楚如何让“系统”为我做后台工作以实现我想要的,通过使用内置的方法和关键字,如线程、同步等。我相信可以做到。只是除了你@user3934037,没有人真正愿意提供帮助。我非常感谢你,我的朋友!不管怎样,我终于搞定了!我用我自己的技巧来解决它。 ;)
【解决方案2】:
猜你喜欢
  • 2017-03-07
  • 2014-02-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-08
  • 1970-01-01
  • 1970-01-01
  • 2021-08-28
相关资源
最近更新 更多