On the JAVA platform, the roles that implement asynchronous calls have the following three roles:
The caller's pickup voucher real data
When a caller calls time-consuming operation and cannot return data immediately, he first returns a pickup voucher. Then, after a break, the real data is obtained with the pickup voucher.
When calling a method, the program will enter the called method body. After executing the called method, it will return to execute the next statement. How to do it like ajax asynchronous request, after sending the request, it executes the next statement without waiting for the request response? For the asynchronous request of java, I found many textbooks but couldn't find it, such as thinking in java, core java2..... .etc. Inspired by multi-threaded download tools and mootools' Request, I made a Java version of Request, but I don't know how its performance is.
Request: Request vector
public class Request { private RequestContent rc;//Request body public Request(RequestContent rc){ this.rc=rc; } protected void start(){ //Start request final Threa d t=new Thread(new Runnable(){ public void run(){ try{ rc.doSomeThing();//Respond to request}catch (Exception e) { e.printStackTrace(); rc.onFailure(); //If execution fails} rc.onSuccess();//If Execution is successful}} ); t.start(); }} RequestContent: Request principal
abstract class RequestContent { void onSuccess(){ //Execute successful action. Users can override this method System.out.println("onSuccess"); } void onFailure(){ //Execute failed action. Users can override this method System.out.println("onFailure"); } abstract void doSomeThing(); //The user must implement this abstract method to tell the child thread what to do} Test: Test
new Request(new RequestContent(){ void doSomeThing(){ System.out.println("doSomething"); } void onSuccess(){ System.out.println("override onSu ccess"); } }).start();The above code is the asynchronous call of java that the editor shared with you. I hope you like it.