本文介绍了在lambda表达式中使用非最终循环变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过执行程序并运行可并行执行100个任务,该任务需要使用循环变量:

I'm trying to execute 100 tasks all in parallel via executors and runnable, the task needs to use the loop variable:

for (int i = 0; i < 100; i++) {
   executor.execute(() -> {
     doSomething(String.format("Need task number %d done", i));
   }
  });
}

我在'i'的语气中迷惑不解-Variable used in lambda expression should be effectively final.

I get a squiggly under 'i' saying - Variable used in lambda expression should be effectively final.

据我所知,不能将循环变量设为final或有效地final,因为每次迭代都会对其进行更改.我找到了一个简单的解决方法,

A loop variable, as far as I'm aware, cannot be made final or effectively final, since it is being changed with each iteration. I found a simple workaround,

for (int i = 0; i < 100; i++) {
   int index = i;
   executor.execute(() -> {
     doSomething(String.format("Need task number %d done", index));
   }
 });
}

对于我来说,这似乎不是最有效的解决方案,每次迭代都声明一个新变量.有更好的方法吗?

This doesn't seem the most effective solution to me, declaring a new variable at every iteration. Is there a better way of doing this?

推荐答案

我对此表示怀疑.您的解决方案对我来说看起来不错,但是如果您愿意,可以将其重写为可能更清晰的代码,例如:

I doubt it. Your solution looks fine to me, but if you want you can rewrite it into possibly clearer code like:

IntStream.range(0, 100).forEach(
    i -> executor.execute(
        () -> doSomething(String.format("Need task number %d done", i))
    )
);

这篇关于在lambda表达式中使用非最终循环变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 06:50