A method for implementing asynchronous invocation in Java multithreading _java

Source: Internet
Author: User

In the Java platform, the role of implementing an asynchronous invocation has the following three roles: caller Bill of lading real data

When a caller invokes a time-consuming operation and cannot return data immediately, a bill of lading is returned first. And then get the real data by Bill of lading after a break.
Go to the cake shop to buy the cake, do not need to wait for the cake to make out (suppose it is a long time), only need to get a bill of lading to be able (to do other things), wait until the cake is ready, then take the bill of lading to take the cake.

public class Main {public  
  static void Main (string[] args) {  
    System.out.println ("Main BEGIN");  
    Host host = new host ();  
    Data data1 = host.request ("A");  
    Data data2 = host.request (' B ');  
    Data data3 = host.request (' C ');  
    System.out.println ("main otherjob BEGIN");  
    try {  
      thread.sleep;  
    } catch (Interruptedexception e) {  
    }  
    System.out.println ("main otherjob End ");  
    System.out.println ("data1 =" + data1.getcontent ());  
    System.out.println ("data2 =" + data2.getcontent ());  
    System.out.println ("data3 =" + data3.getcontent ());  
    System.out.println ("main End");  
  }  

The main class here is the equivalent of "customer", host is equivalent to "cake shop", the customer to "cake shop" to set the cake is equivalent to "request requests", returned data is Futuredata instance, is equivalent to the bill of lading, rather than the real "cake." After a period of time (sleep for some time), call Data1.getcontent (), that is, take the bill of lading to obtain execution results.

Here's a look at what the cake shop did after the customer set the cake:

public class Host {public  
  Data request (final int count, final char c) {  
    System.out.println ("request" + Count +) , "+ C +") BEGIN ");  
    (1) The establishment of Futuredata entity  
    final Futuredata future = new Futuredata ();  
    (2) to create a realdata entity, start a new thread  
    () {public                     
      void run () {  
       ///Use count, future, C in an anonymous inner class.            
        realdata realdata = new Realdata (count, c);  
        Future.setrealdata (Realdata);  
      }                         
    . Start ();                       
    SYSTEM.OUT.PRINTLN ("Request (" + Count + "," + C + ") end");  
    (3) Retrieving the Futuredata entity as the return value  returns  
    future;  
  }  

Host ("Cake Shop") after receiving the request, the gentleman became "the bill of Lading" futuredata instance future, then ordered "the Cake Master" Realdata to make the cake, Realdata is equivalent to a thread to make the cake. Then the host returns to the customer only the "Bill of Lading" future, not the cake. When the cake is done, the cake master can give the corresponding "Bill of lading" cake, namely Future.setrealdata (Realdata).

Now let's see how the cake maker made the cake:

Create a string that contains the count of C characters, which takes some time to show the law, and uses sleep.

public class Realdata implements Data {  
  private final String content;  
  public realdata (int count, char c) {  
    System.out.println ("Making realdata (" + Count + "," + C + ") BEGIN");  
    char[] buffer = new Char[count];  
    for (int i = 0; i < count; i++) {  
      buffer[i] = c;  
      try {  
        thread.sleep (1000);  
      } catch (Interruptedexception e) {  
      }  
    }  
    System.out.println ("Making Realdata ("+ Count +", "+ C +") end ");  
    This.content = new String (buffer);  
  Public String getcontent () {return  
    content;  
  }  
}

Now let's see how the "Bill of lading" future corresponds to the cake "content":

public class Futuredata implements Data {  
  private realdata realdata = null;  
  Private Boolean ready = false;  
  Public synchronized void Setrealdata (Realdata realdata) {  
    if (ready) {return              
      ;   Prevent Setrealdata from being invoked more than two times. 
    }  
    This.realdata = Realdata;  
    This.ready = true;  
    Notifyall ();  
  }  
  Public synchronized String getcontent () {while  
    (!ready) {  
      try {wait  
        ();  
      } catch ( Interruptedexception e) {  
      }  
    } return  
    realdata.getcontent ();  
  }  

When the customer finishes his own business, he takes his "Bill of lading" to fetch the cake:


  

At this time if the cake is not ready, we have to wait:

while (!ready) {  
      try {  
        wait ();  
      } catch (Interruptedexception e) {  
      }  
//etc to be fetched   

Program Analysis

For each request, host generates a thread that is responsible for generating the "cake" that the customer needs. After waiting for some time, if the cake is not ready, the customer must wait. Until "The cake is done", namely Future.setrealdata (Realdata); After execution, the customer can take the cake.

Each thread is solely responsible for making the "cake" needed for a particular customer. That is, customer a corresponds to the cake master A, customer B corresponds to the cake Master B. Even if customer B's cake is done first, customer a can only wait for cake master A To do the cake well. In other words, there is no competitive relationship between customers.

The two methods of class Futuredata are set to synchronized, in fact, the mutual exclusion between cake master A and customer A, that is, customer a must wait for cake master A to finish the cake before it can be taken away, and it has nothing to do with cake Master B.

This is the end of this article, the code is simple, I hope that you learn Java multithreaded implementation of asynchronous calls help, thank you.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.