英文:
spring boot loop in @async mulit-thread
问题
如果我在调用doSomething()时提供索引值,索引值将为100。如何解决这个问题?
我希望索引为0、1、2、3、4。
List<CompletableFuture> futures = new ArrayList();
for (int i = 0; i < 5; i++) {
int index = i; // Capture the current value of 'i'
futures.add(CompletableFuture.runAsync(() -> doSomething(index)));
futures.add(CompletableFuture.runAsync(() -> doSomethingElse(index)));
}
CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).thenRunAsync(() -> log("已完成操作"));
英文:
If I give the index value when I call doSomething(), the index value is 100. How to solve it?
I want the index to be 0,1,2,3,4
List<CompletableFuture> futures = new ArrayList();for(
int i = 0;i<100;i++)
{
futures.add(CompletableFuture.runAsync(() -> doSomething(i)));
futures.add(CompletableFuture.runAsync(() -> doSomethingElse(i)));
}CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).thenRunAsync(()->log("Ended doing things"));
答案1
得分: 2
变量i
必须是final
或者effectively final
。你可以使用类似于AtomicInteger
的东西,或者对它进行复制,例如:
List<CompletableFuture<Void>> futures = new ArrayList<>();
for (int i = 0; i < 100; i++) {
int finalI = i;
futures.add(CompletableFuture.runAsync(() -> doSomething(finalI)));
futures.add(CompletableFuture.runAsync(() -> doSomethingElse(finalI)));
}
CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).thenRunAsync(() -> log("Ended doing things"));
英文:
Variable i
must be final
or effectively final
. You can use somethink like AtomicInteger
or make copy of it e.g.
List<CompletableFuture<Void>> futures = new ArrayList<>();
for (int i = 0; i < 100; i++) {
int finalI = i;
futures.add(CompletableFuture.runAsync(() -> doSomething(finalI)));
futures.add(CompletableFuture.runAsync(() -> doSomethingElse(finalI)));
}
CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).thenRunAsync(() -> log("Ended doing things"));
专注分享java语言的经验与见解,让所有开发者获益!
评论