JAVA implements asynchronous invocation of instance code
- 2020-04-01 04:13:11
- OfStack
In the JAVA platform, there are three roles that implement asynchronous invocation:
Invoker receipt & payment; Real data
When a caller cannot return the data immediately due to the time consuming operation, it first returns a collection voucher, and then obtains the real data with the collection voucher after a period of time.
When a method is called, the program enters the body of the called method, executes the called method, and returns to execute the next statement. How do you do asynchronous requests like ajax, where the request is sent and the next statement is executed before the request is answered? For the asynchronous request of Java, I found a lot of teaching materials, such as thinking in Java, core java2...... And so on. Inspired by the multi-threaded download tool and mootools' Request, I made a Java version of Request, I wonder how it performs.
Request: Request carrier
public class Request {
private RequestContent rc;//Request body
public Request(RequestContent rc){
this.rc=rc;
}
protected void start(){ //To request
final Thread t=new Thread(new Runnable(){
public void run(){
try{
rc.doSomeThing();//Respond to the request
}catch (Exception e) {
e.printStackTrace();
rc.onFailure(); //If the execution fails
}
rc.onSuccess();//If it works
}}
);
t.start();
}
}
RequestContent: request body
abstract class RequestContent {
void onSuccess(){ //Execute the successful action. Users can override this method
System.out.println("onSuccess");
}
void onFailure(){ //Execute the failed action. Users can override this method
System.out.println("onFailure");
}
abstract void doSomeThing(); //The user must implement this abstract method, telling the child thread what to do
}
The Test: testing
new Request(new RequestContent(){
void doSomeThing(){
System.out.println("doSomething");
}
void onSuccess(){
System.out.println("override onSuccess");
}
}).start();
The above code is this site to share the Java asynchronous call, I hope you like.