在Java中等待的最佳方式
发布时间:2020-12-15 08:47:53 所属栏目:Java 来源:网络整理
导读:我有一个需要等待一段时间的应用程序.它必须等到服务器填充几个数据字段. 服务器的API为我提供了一种请求数据的方法,很简单…… 服务器的API还提供了一种接收我的数据的方法,一次一个字段.它并没有告诉我何时完成所有字段的填充. 在我的请求完成服务器处理之
我有一个需要等待一段时间的应用程序.它必须等到服务器填充几个数据字段.
服务器的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()时检查是否具有所有必需的值? 什么是最好的方法?谢谢. 解决方法
如果我理解正确,其他一些线程会在MyApp上调用receiveData来填充数据.如果这是对的,那么这就是你如何做到的:
>你像这样睡觉: do { this.wait(someSmallTime); //We are aquiring a monitor on "this" object,so it would require a notification. You should put some time (like 100msec maybe) to prevent very rare but still possible deadlock,when notification came before this.wait was called. } while (!allFieldsAreFilled()); > receiveData应该进行通知呼叫,以取消暂停您的等待呼叫.例如这样: myData.put(field,value); this.notify(); >两个块都需要在此对象上“同步”才能获取它的监视器(等待时需要).您需要将方法声明为“synchronized”,或将相应的块放在synchronized(this){…}块中. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |