在我的程序中,我连接到另一种语言的解释器进程。有时我需要程序向解释器询问一些事情并使用它的响应。
进程存储在 IProcess 变量中,并且通过进程的 IStreamsProxy 完成通信。为了接收响应,我向 IStreamsProxy 添加了一个 IStreamListener。
但是,当我写入 IStreamsProxy(使用 write() 方法)时,我需要代码来等待响应,例如要调用的监听器的streamAppend方法。
我尝试使用wait()和notify()方法,但我不知道应该在哪些对象上调用它们。
进行通信的查询类调用如下方法:
/**
* Sends a command to the interpreter. Makes the current thread wait for an answer of the interpreter.
* @throws IOException
*/
private synchronized void send(String command) throws IOException{
this.s48Proxy.write(command);
try {
System.out.println("waiting for reply");
this.wait();
} catch (InterruptedException e) {
System.out.println("interruption exception: "+e.getMessage());
}
}
和听众:
private class Listener implements IStreamListener {
private Query query;
public Listener(Query query) {
super();
this.query = query;
}
@Override
public void streamAppended(String arg0, IStreamMonitor arg1) {
System.out.println("got interpreter answer");
query.setCurrentOutput(arg0.substring(0, arg0.lastIndexOf("\n")).trim());
query.notify();
}
}
streamAppend()
方法调用查询类上的 notify()
方法。然而,这是行不通的。 “等待回复”是我收到的最后一条回复。
我该怎么做?或者我可以使用任何其他方法来自动实现此目的吗?
最佳答案
您可以使用Object#wait
和Object#notifiy
。
// @ IStreamsProxy
synchronized( someMonitor ) {
someMonitor.wait( /* time? */ );
}
// @ Listener
synchronized( someMonitor ) {
someMonitor.notify();
}
-> Javadoc Link
关于java让一个方法等待另一个进程的响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7713786/