Sure, here’s the translation: “Spring Boot在@Async多线程中的循环。”

huangapple go评论95阅读模式
英文:

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&lt;CompletableFuture&gt; futures = new ArrayList();for(
int i = 0;i&lt;100;i++)
{
	futures.add(CompletableFuture.runAsync(() -&gt; doSomething(i)));
	futures.add(CompletableFuture.runAsync(() -&gt; doSomethingElse(i)));
}CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).thenRunAsync(()-&gt;log(&quot;Ended doing things&quot;));

答案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&lt;CompletableFuture&lt;Void&gt;&gt; futures = new ArrayList&lt;&gt;();
for (int i = 0; i &lt; 100; i++) {
    int finalI = i;
    futures.add(CompletableFuture.runAsync(() -&gt; doSomething(finalI)));
    futures.add(CompletableFuture.runAsync(() -&gt; doSomethingElse(finalI)));
}
CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).thenRunAsync(() -&gt; log(&quot;Ended doing things&quot;));

huangapple
  • 本文由 发表于 2020年7月24日 16:58:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/63070284.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定