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.