我有一个应用程序需要等待某个未知的时间。它必须等到服务器填充完几个数据字段。
服务器的API提供了一种请求数据的方法,非常简单...
服务器的API还提供了一种逐个返回我的数据的方式。但它没有告诉我所有字段何时全部填充完成。
最有效的等待服务器处理完我的请求的方法是什么?以下是一些伪代码:
public class ServerRequestMethods {
public void requestData();
}
public interface ServerDeliveryMethods {
public void receiveData(String field, int value);
}
public class MyApp extends ServerRequestMethods implements ServerDeliveryMethods {
//store data fields and their respective values
public Hashtable<String, Integer> myData;
//implement required ServerDeliveryMethods
public void receiveData(String field, int value) {
myData.put(field, value);
}
public static void main(String[] args) {
this.requestData();
// Now I have to wait for all of the fields to be populated,
// so that I can decide what to do next.
decideWhatToDoNext();
doIt();
}
}
我必须等到服务器完成填充我的数据字段,但服务器不会告诉我请求何时完成。因此,我必须不断检查我的请求是否已完成处理。最有效的方法是什么?
使用wait()和notify(),并使用一个方法来保护while循环,每次被notify()唤醒时检查是否已经拥有所有所需的值?
使用Observer和Observable,使用一个方法,在每次调用Observer.Update()时检查是否已经拥有所有所需的值?
哪种方法最好?谢谢。
decideWhatToDoNext()
方法。 - Perception