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