我找到了一些答案,例如“等待,通知,同步,线程等”,但不确定如何将其应用到我的代码中。在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");
}

最佳答案

wait()方法意味着您要等到资源未被锁定为止。 notify()意味着您现在要退出关键部分并释放资源。
因此,如果要等到发送一个数据,则必须先进入关键部分,然后再发送消息,然后在所有消息都发送之后才从关键部分中退出。
我认为您必须在每次调用SendCommand(“ content”)的第一个调用wait(),并在SendCommand方法的末尾调用notify函数。

10-05 23:24