0

I would like to get result from each callable task that are already submitted to a pool.

Eg:

  • I have 5 callable task, Each task wait for 5 seconds

  • I Submitted 5callable task to fixed thread pool 5

  • Shall i get notification if 2 nd callable task completes its work ?

    public class MyCallable implements Callable<Result> {
    
        Result result =null;
        public MyCallable(int id, String name) {
            result=new Result(id, name);
        };
    
        @Override
        public Result call() throws Exception {
            Thread.sleep(5000);
            return result;
        }
    
        public static void main(String args[]){
            ExecutorService executor = Executors.newFixedThreadPool(10);
            List<Future<Result>> list = new ArrayList<Future<Result>>();
            Callable<Result> callable = null; 
    
            for(int i=0; i< 10; i++){
              callable = new MyCallable( i, "t"+i);
              Future<Result> future = executor.submit(callable);
              list.add(future);
            }
    
            for(Future<Result> fut : list){
              try {
                 Result res = fut.get();
                 System.out.println(new Date()+" Thread name "+res.getName() +" ID "+res.getId());
              } catch (InterruptedException | ExecutionException e) {
                 e.printStackTrace();
            }
       }
       executor.shutdown();
     }
    
    }
    
    class Result {
    
      int id;
      String name;
    
      public int getId() {
        return id;
      }
    
      public String getName() {
        return name;
      }
    
      public Result(int id, String name) {
         super();
         this.id = id;
         this.name = name;
      }
    
    }  
    

In the above example future.get method will call after processing 5 threads by excutor service.

Vaseph
  • 704
  • 1
  • 8
  • 20
Amith
  • 1,907
  • 5
  • 29
  • 48
  • It's not clear what you want to do. You want to be notified when each tasks finishes it's job or when all are done? – Slimu Aug 23 '16 at 12:14
  • @Slimu I want to be notified when each tasks finishes it's job – Amith Aug 23 '16 at 12:41
  • See this answer: http://stackoverflow.com/questions/6346927/java-callable-futuretask-excecuter-how-to-listen-to-finished-task?rq=1 – Slimu Aug 23 '16 at 14:25

0 Answers0