我有 2 个线程,一个用于传输,一个用于重播我只想在 RXThread 上收到一条消息时发送一条消息。我使用了 wait() 和 notify(),为了防止在 wait() 之前出现通知,我这样做了,但它仅在调试中运行时才有效,尽管 RX 线程不发送消息。
private boolean stopped = false;
class StubTxtask implements Runnable {
public void run() {
try {
// Sends all messages in sequence
for (int i=0; i<txMsgSeq.getMessagesCount(); i++) {
}
if (syncRxTx) {
synchronized (syncObj) {
while(!stopped) {
syncObj.wait();
}
}
}
System.out.println("************ "+ i + "/" + txMsgSeq.getMessagesCount());
pcs.sendMsg((GeneratedMessage)txMsgSeq.getMessage(i));
if (!syncRxTx) {
Thread.sleep(1000);
}
}
} catch (Exception e) {
}
}
}
class StubRxtask implements Runnable {
public void run() {
while (true) {
try {
// Wait for a message()
TncMessage msg = (TncMessage) pcs.waitMsg(connInt);
System.out.println(msg.toString());
// Add the message to the RX Sequence
rxMsgSeq.addMessage(msg);
System.out.println(rxMsgSeq.getMessagesCount());
if (syncRxTx) {
TncHeader header;
Method invokeGetHeader;
try {
invokeGetHeader = msg.getClass().getMethod("getHeader", null);
header = (TncHeader) invokeGetHeader.invoke(msg, null);
if (header.getType() != EnumMessageType.ACK) {
synchronized (syncObj) {
stopped = true;
syncObj.notify();
}
}
} catch (Exception e) {
System.err.println("ERROR - Impossible to find or invoke getHeader() method on msg");
}
}
stopped = false;
} catch (Exception e) {
}
}
}
}