Mode 9-Future

Source: Internet
Author: User

Come to Java multi-thread design mode

For a method that takes some time to execute, instead of waiting for the execution result to come out, it gets an alternative "Bill of Lading ".

Use Asynchronous Method call to separate the prepared and returned values.

 Public   Class Main { Public   Static   Void Main (string [] ARGs) {system. Out. println (" Main begin "); Host = New Host (); Data data1 = host. request (10, 'A'); Data data2 = host. request (20, 'B'); Data data3 = host. request (30, 'C '); System. Out. println (" Main otherjob begin ");Try {Thread. Sleep (2000 );} 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 ");}}

 

 Public   Class FuturedataImplements Data { Private Realdata = Null ; Private   Boolean Ready = False ; Public   Synchronized   Void Setrealdata (realdata ){ If (Ready ){ Return ; // Balk }This . Realdata = realdata; This . Ready = True ; Policyall ();} Public   Synchronized String getcontent (){ While(! Ready ){Try{Wait ();}Catch(Interruptedexception e ){}}          Return Realdata. getcontent ();}}
 
Host class
 Public   Class Host {PublicData Request (Final IntCount,Final CharC) {System. Out. println (" Request ( "+ Count +" , "+ C +" ) Begin "); // (1) Establish the object of futuredata          Final Futuredata future = New Futuredata (); // (2) Start a new thread to establish the realdata entity          New Thread (){ Public   Void Run (){ Realdata =NewRealdata (count, c); future. setrealdata (realdata ); }. Start (); system. Out. println (" Request ( "+ Count +" , "+ C +" ) End "); // (3) retrieve the futuredata object as the return value          Return Future ;}}

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.