Return values from Java Threads

后端 未结 9 1410
耶瑟儿~
耶瑟儿~ 2020-12-13 07:12

I have a Java Thread like the following:

   public class MyThread extends Thread {
        MyService service;
        String id;
        public MyThread(Stri         


        
9条回答
  •  醉话见心
    2020-12-13 08:04

    If you want to collect all of the results before doing the database update, you can use the invokeAll method. This takes care of the bookkeeping that would be required if you submit tasks one at a time, like daveb suggests.

    private static final ExecutorService workers = Executors.newCachedThreadPool();
    
    ...
    
    Collection> tasks = new ArrayList>();
    for (final String id : ids) {
      tasks.add(new Callable()
      {
    
        public User call()
          throws Exception
        {
          return svc.getUser(id);
        }
    
      });
    }
    /* invokeAll blocks until all service requests complete, 
     * or a max of 10 seconds. */
    List> results = workers.invokeAll(tasks, 10, TimeUnit.SECONDS);
    for (Future f : results) {
      User user = f.get();
      /* Add user to batch update. */
      ...
    }
    /* Commit batch. */
    ...
    

提交回复
热议问题