The best way to wait in Java

I have an application that needs to wait for some time It must wait until the server fills in several data fields

The server API provides me with a method to request data. It's very simple

The server API also provides a way to receive my data, one field at a time It doesn't tell me when to complete the filling of all fields

What is the most effective method before my request is processed by the server? These are pseudocodes:

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();
    }
}

I have to wait until the server completes filling in my data fields, and the server won't let me know when the request is completed So I must continue to check whether my request has been processed What is the most effective way?

Wait () and notify () are methods that guard the while loop. Whenever I wake up by notify (), check whether I have all the necessary values?

Observer and observable, there is a method that can call observer every time Check for all required values when updating()?

What is the best way? thank you.

Solution

If I understand correctly, some other threads will call receivedata on myapp to fill in the data If that's right, then that's how you do it:

>You sleep like this:

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 should make a notification call to cancel suspending your waiting call For example:

myData.put(field,value);   
this.notify();

>Both blocks need to be "synchronized" on this object to get its monitor (required while waiting) You need to declare the method "synchronized", or put the corresponding block in the synchronized (this) {...} block

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>