java使一个方法等待另一个进程的响应 [英] 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.
进程存储在 IProcess 变量中,通信通过进程的 IStreamsProxy 完成.为了接收响应,我向 IStreamsProxy 添加了一个 IStreamListener.
The process is stored in a IProcess variable and the communication is done via the IStreamsProxy of the process. to recieve the response, I added an IStreamListener to the IStreamsProxy.
但是,当我写入 IStreamsProxy(使用 write() 方法)时,我需要等待响应的代码,例如要调用的侦听器的 streamAppend 方法.
However, when I write to the IStreamsProxy (with the write() method), I need the code to wait for the response, e.g. the streamAppend-method of the listener to be called.
我尝试使用 wait() 和 notify() 方法,但我不知道应该在哪些对象上调用它们.
I tried to use the wait() and notify() method, but I don't know on what objects I should call them.
进行通信的查询类调用如下方法:
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());
}
}
和听众:
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()
方法.但是,这不起作用.等待回复"是我得到的最后一个回复.
The streamAppend()
method calls the notify()
-method on the query class. 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?
推荐答案
你可以使用 Object#wait
&对象#notify
.
You could use Object#wait
& Object#notifiy
.
// @ IStreamsProxy
synchronized( someMonitor ) {
someMonitor.wait( /* time? */ );
}
// @ Listener
synchronized( someMonitor ) {
someMonitor.notify();
}
-> Javadoc 链接
这篇关于java使一个方法等待另一个进程的响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!