[英]java make a method wait for a response of another process
In my program, I connect to an interpreter process for another language. 在我的程序中,我连接到另一种语言的解释程序。 I need the program sometimes to ask the interpreter several things and use it's response. 有时我需要程序向解释器询问几件事并使用它的响应。
The process is stored in a IProcess variable and the communication is done via the IStreamsProxy of the process. 该过程存储在IProcess变量中,并且通过该过程的IStreamsProxy完成通信。 to recieve the response, I added an IStreamListener to the IStreamsProxy. 为了收到响应,我在IStreamsProxy中添加了一个IStreamListener。
However, when I write to the IStreamsProxy (with the write() method), I need the code to wait for the response, eg the streamAppend-method of the listener to be called. 但是,当我使用write()方法写入IStreamsProxy时,我需要等待等待响应的代码,例如,将调用侦听器的streamAppend方法。
I tried to use the wait() and notify() method, but I don't know on what objects I should call them. 我尝试使用wait()和notify()方法,但是我不知道应该调用哪些对象。
The query class which makes the communication calls a method like this: 使通信进行通信的查询类将调用以下方法:
/**
* 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());
}
}
and the listener: 和听众:
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();
}
}
The streamAppend()
method calls the notify()
-method on the query class. streamAppend()
方法在查询类上调用notify()
方法。 However, this does not work. 但是,这不起作用。 "Waiting for reply" is the last response I get. 我最后得到的回复是“等待回复” 。
How can I do this? 我怎样才能做到这一点? Or are there any other methods I could use to achieve this automatically? 还是我可以使用其他方法自动实现此目的?
You could use Object#wait
& Object#notifiy
. 您可以使用Object#wait
和Object#notifiy
。
// @ IStreamsProxy
synchronized( someMonitor ) {
someMonitor.wait( /* time? */ );
}
// @ Listener
synchronized( someMonitor ) {
someMonitor.notify();
}
-> Javadoc Link -> Javadoc链接
Use a semaphore like boolean waitingForResponse. 使用诸如boolean WaitingForResponse之类的信号量。 Set this to true when you make your call, then go into 拨打电话时将其设置为true,然后进入
while(waitingForResponse){ sleep(99) //should be your average response time from your call } while(waitingForResponse){sleep(99)//应该是您通话的平均响应时间}
In your listener, set waitinForResponse to false. 在您的侦听器中,将waitinForResponse设置为false。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.