我有以下代码。我想在执行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
}
}
错误是
在封闭范围内定义的局部变量i必须是final或 有效地最终
方法如下
@Service
class Other {
void m1() {
}
String m2() {
return "Hello";
}
int m3(int n) {
return n;
}
}
答案 0 :(得分:1)
尝试一下:
void test_method() {
for (int i = 0; i < 201; i++) {
executorService.submit(other::m1);
executorService.submit(other::m2);
final int i1 = i;
executorService.submit(() -> other.m3(i1));
}
}
答案 1 :(得分:1)
在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));
});