在每个任务完成后从callable获取结果

时间:2016-08-23 12:05:49

标签: java multithreading callable

我想从已提交到池的每个可调用任务中获得结果。

例如:

  • 我有5个可调用任务,每个任务等待5秒

  • 我将5callable任务提交给固定的线程池5

  • 如果第二个可调用任务完成其工作,我会收到通知吗?

    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;
      }
    
    }  
    

在上面的例子中,future.get方法将在激励服务处理5个线程后调用。

0 个答案:

没有答案