Concurrent time-consuming computational simulations

Source: Internet
Author: User

Tag:futuretask    concurrent    

Import Java.util.random;import Java.util.concurrent.callable;import java.util.concurrent.ExecutionException; Import Java.util.concurrent.futuretask;public class Futuretaskdemo {public static void main (string[] args) {// Initializes a callable object and Futuretask object callable Paccount = new Privateaccount (); Futuretask futuretask = new Futuretask (paccount);//Use Futuretask to create a thread for threads paccountthread = new Thread (futuretask); System.out.println ("Futuretask thread starts now, startup time:" + system.nanotime ());p Accountthread.start (); System.out.println ("Main thread begins to perform other tasks");//Get total amount from other accounts int totalmoney = new Random (). Nextint (100000); System.out.println ("Now your total amount in other accounts is" + Totalmoney); System.out.println ("Wait for the total amount of the private account to be counted ...");//test the background of the calculation thread is complete, if not completed wait while (!futuretask.isdone ()) {try {thread.sleep ( 500); System.out.println ("Private account calculation not completed continue waiting ..."); catch (Interruptedexception e) {e.printstacktrace ();}} System.out.println ("Futuretask thread is calculated, this time is" + system.nanotime ()); Integer Privateaccountmoney = null;try { Privateaccountmoney = (Integer) futuretask.gET ();} catch (Interruptedexception e) {e.printstacktrace ();} catch (Executionexception e) {e.printstacktrace ();} System.out.println ("Your current total amount is:" + totalmoney+ Privateaccountmoney.intvalue ());}} @SuppressWarnings ("All") class Privateaccount implements callable {Integer totalmoney;public Object call () throws Exception {thread.sleep; Totalmoney = new Integer (new Random (). Nextint (10000)); System.out.println ("You currently have" + Totalmoney + "in your private Account"); return Totalmoney;}}

Concurrent time-consuming computational simulations

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.