有以下列表,
List shardingCreateTablesList = new ArrayList();
shardingCreateTablesList.add(“tb1”);
shardingCreateTablesList.add(“tb2”);
shardingCreateTablesList.add(“tb3”);
shardingCreateTablesList.add(“tb4”);
shardingCreateTablesList.add(“tb5”);
shardingCreateTablesList.add(“tb6”);
shardingCreateTablesList.add(“tb7”);
shardingCreateTablesList.add(“tb8”);
异步执行
List<Future<?>> futures = Lists.newArrayList(); for (int i = 0; i < shardingCreateTablesList.size(); i++) {//遍历分表的物理表 int finalI = i; Future<?> future = shardingTableExecutor.submit(() -> {
// 执行具体的任务并返回结果
this.doTask(shardingCreateTablesList.get(finalI), finalI);
});
futures.add(future);
}
但是tb8的元素,却被执行了2遍,
是什么原因呢?
解决
以下2种方式都可以
List<Future<?>> futures = new ArrayList<>();
IntStream.range(0, shardingCreateTablesList.size()).forEach(i -> {Future<?> future = shardingTableExecutor.submit(() -> {this.mysqlShardingDDLByGoInception(shardingCreateTablesList.get(i), i);});futures.add(future);});
List<Future<?>> futures = Lists.newArrayList();
AtomicInteger index = new AtomicInteger();
for (String tableName : shardingCreateTablesList) {Future<?> future = shardingTableExecutor.submit(() -> {this.mysqlShardingDDLByGoInception(tableName, index.getAndIncrement());});futures.add(future);
}