java make a method等待另一个进程的响应
在我的程序中,我连接到另一种语言的解释器进程。 我有时需要程序向解释器询问几件事并使用它的响应。
该过程存储在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
使用像boolean waitingForResponse这样的信号量。 拨打电话时将此设置为true,然后进入
while(waitingForResponse){sleep(99)//应该是你通话的平均响应时间}
在您的侦听器中,将waitinForResponse设置为false。