Return values from Java Threads

后端 未结 9 1379
耶瑟儿~
耶瑟儿~ 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 07:59

    The simplest approach is to pass an object to each thread (one object per thread) that will contain the result later. The main thread should keep a reference to each result object. When all threads are joined, you can use the results.

    0 讨论(0)
  • 2020-12-13 08:02

    You could create a queue or list which you pass to the threads you create, the threads add their result to the list which gets emptied by a consumer which performs the batch insert.

    0 讨论(0)
  • 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<Callable<User>> tasks = new ArrayList<Callable<User>>();
    for (final String id : ids) {
      tasks.add(new Callable<User>()
      {
    
        public User call()
          throws Exception
        {
          return svc.getUser(id);
        }
    
      });
    }
    /* invokeAll blocks until all service requests complete, 
     * or a max of 10 seconds. */
    List<Future<User>> results = workers.invokeAll(tasks, 10, TimeUnit.SECONDS);
    for (Future<User> f : results) {
      User user = f.get();
      /* Add user to batch update. */
      ...
    }
    /* Commit batch. */
    ...
    
    0 讨论(0)
提交回复
热议问题