【发布时间】:2020-09-23 12:01:31
【问题描述】:
我有以下代码。在执行 m1 和 m2 时,我想通过 3 个线程并行执行 m3()。
我怎样才能实现它。我正在使用 Spring Boot 和 java 8。是否可以使用执行器服务执行 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
}
}
错误是
我在封闭范围内定义的局部变量必须是最终的或 有效地最终
方法如下
@Service
class Other {
void m1() {
}
String m2() {
return "Hello";
}
int m3(int n) {
return n;
}
}
【问题讨论】:
-
错误是什么?
-
Local variable i defined in an enclosing scope must be final or effectively final
标签: java spring multithreading spring-boot parallel-processing