我有一个使用axis2的异步Web服务,我使用相同的CallBack Hanlder调用两次不同的时间,如下所示:
stub.startGetData("Foo",callbackhandler)
stub.startGetData("bar",callbackhanlder)
ServiceCallBackhandler callbackhandler = new ServiceCallBackhandler() { .....};
//ServiceCallBackhanlder and stub are generated from a WSDL file
Synchronized(callbackhandler){ callbackhandler.wait()}
//remaining code to be executed
............
...........
这种情况下的问题是,一旦呼叫在stub.startGetData("Foo",callbackhandler)
之后返回,就会执行“剩余代码”。我希望回调等到它还完成处理stub.startGetData("boo",callbackhandler)
语句然后执行剩余的代码。有没有办法在不使用两个不同的回调函数的情况下完成它,因为两个返回值的处理是相同的。感谢。
答案 0 :(得分:2)
我想你想要这样的东西......
import java.util.concurrent.CountDownLatch;
...
// set the latch count to the nuber of callbacks to wait for
CountDownLatch latch = new CountDownLatch(2);
ServiceCallBackhandler callbackhandler = new ServiceCallBackhandler() {
public void handleResponse(Response response) {
.... do real work ...
latch.countDown();
}
};
stub.startGetData("Foo",callbackhandler)
stub.startGetData("bar",callbackhanlder)
// wait for both callbacks to occur
latch.await();
另请参阅java.util.concurrent.Semaphore,但我认为CountDownLatch是您所描述的内容。
答案 1 :(得分:0)
一般来说,如果想要等到N个不同对象的特定条件成立,他们应该考虑使用并发工具中的CyclicBarrier(N)或CountDownLatch(N)。
主体的基本结构:
CountDownLatch my_latch = new CountDownLatch( 2 );
// These objects perform some asynchronous function when
// their start() method is called.
AsyncObject ao1 = new AsyncObject( my_latch, ... );
AsyncObject ao2 = new AsyncObject( my_latch, ... );
ao1.start(); // asynchronous, returns immediately
ao2.start(); // asynchronous, returns immediately
// my_latch.await() blocks until the latch has counted down to 0 from 2
my_latch.await();
从希望在其工作完成或满足条件时“发出信号”的方法中:
{
// ... work ...
// work is complete
the_latch_passed_in_to_this_object.countDown();
}