1 package com.test; 2 3 import java.util.Random; 4 import java.util.concurrent.Callable; 5 import java.util.concurrent.ExecutionException; 6 import java.util.concurrent.Executor; 7 import java.util.concurrent.Future; 8 import java.util.concurrent.FutureTask; 9 import java.util.concurrent.ScheduledThreadPoolExecutor; 10 11 public class MyObject { 12 13 public static Executor ex = new ScheduledThreadPoolExecutor(100); 14 15 public static void main(String[] args) throws InterruptedException, ExecutionException { 16 17 Tracker t = new Tracker(); 18 Future<Tracker> f[] = new Future[1000]; 19 20 for(int i=0;i<1000;i++){ 21 /*The code in MyFutureTask.call() would be executed sometime in the future*/ 22 f[i] = new FutureTask<Tracker>(new MyFutureTask(t)); 23 ex.execute((Runnable) f[i]); 24 } 25 26 /*Wait for all the future task to complete!*/ 27 for(int i=0;i<1000;i++){ 28 f[i].get(); 29 } 30 31 /*Print out the number of future task that we have completed*/ 32 System.out.println(t.getValue()); /*This prints the number of task executed - 1000*/ 33 } 34 } 35 36 class MyFutureTask implements Callable<Tracker>{ 37 38 Tracker myTracker; 39 MyFutureTask(Tracker t) 40 { 41 myTracker = t; 42 } 43 44 @Override 45 public synchronized Tracker call() throws Exception { 46 47 /*Some complex business logic inserted at this point*/ 48 int rand = new Random().nextInt(1000); 49 Thread.sleep(rand); 50 51 myTracker.increment(); 52 return myTracker; 53 } 54 } 55 56 class Tracker{ 57 Integer value = 0; 58 59 public void increment() 60 { 61 value++; 62 } 63 public int getValue(){ 64 return value; 65 } 66 }