我有下面的代码。我要在执行m1和m2时由3个线程并行执行m3()
。
我该如何实现。我正在使用Spring Boot和Java8。是否可以使用执行程序服务执行m3()
。
@Service
class Main {
@Autowired
Private Other other;
ExecutorService executorService = Executors.newFixedThreadPool(3);
void test_method() {
for (int i = 0; i < 201; i++) {
executorService.submit(() -> other.m1()); // works fine as expected
executorService.submit(() -> other.m2()); // works fine as expected
executorService.submit(() -> other.m3(i)); // compilation error as expected
}
}
错误是Local variable i defined in an enclosing scope must be final or effectively final
方法如下
@Service
class Other {
void m1() {
}
String m2() {
return "Hello";
}
int m3(int n) {
return n;
}
}
最佳答案
在Java中,您不能在匿名内部类(即lambda表达式)中使用非最终变量。
一种可能的解决方法是使用
IntStream.range
和IntStream.forEach
方法:IntStream.range(0, 201).forEach(i -> {
executorService.submit(() -> other.m1());
executorService.submit(() -> other.m2());
executorService.submit(() -> other.m3(i));
});
关于java - 带有返回类型和输入参数的Execute方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64027507/