[英]Execute a same method in parallel with different input's using Future and @ Async
[英]Execute method with a return type and input parameter in parallel
我有以下代码。 我想在执行 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;
}
}
尝试这个:
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));
}
}
在 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));
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.