使用ExecutorService和Future的专用方法是什么?

时间:2016-07-15 21:50:41

标签: java future executorservice

我有一批物品。对于每个项目,我可以获取itemID,然后使用此ID进行一些数据库查找并生成此批次的所有事务。

List<BatchItem> batchItemsList; // assume this list already have a list of items       
List<Transaction> results = new ArrayList<>();
ExecutorService executor = Executors.newFixedThreadPool(5);
List<Future<Transaction>> tasks = new ArrayList<>();

for(BatchItem item: batchItemsList) {
    MyThread worker = new MyThread(item);
    Future<Transaction> future = executor.submit(worker);
    tasks.add(future);
}

for(Future<Transaction> t: tasks) {
       results.add(t.get());
}

MyThread.java

public class MyThread implements Callable<Transaction>{
  private final BatchItem batchItem;

  public MyThread(BatchItem batchItem) {
    this.batchItem = batchItem;
  }

  @Override
  public Transaction call() throws Exception {
    String id = batchItem.getId();
    // SQL lookups....
    Transaction t = new Transaction(sql lookup result values...);
    return t;
  }
}

问题1: 我真的需要创建所有MyThread对象吗?如果我有15k项目,这意味着我将在内存中创建15k MyThread对象...解决问题的专用方法是什么?

问题2 我是否需要检查未来是否已完成?如果是这样,我应该如何处理isdone()?

0 个答案:

没有答案