英文:
Execute method with a return type and input parameter in parallel
问题
下面是翻译好的内容:
我有以下的代码。我想通过3个线程并行执行 m3()
,就像我在执行 m1
和 m2
一样。
我该如何实现呢?我正在使用Spring Boot和Java 8。能否使用执行器(Executor Service)来执行 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()); // 正如预期那样工作得很好
executorService.submit(() -> other.m2()); // 正如预期那样工作得很好
executorService.submit(() -> other.m3(i)); // 编译错误,正如预期那样
}
}
错误信息为:
> 定义在封闭作用域中的局部变量 i 必须是 final 或 effectively final
以下是方法:
```java
@Service
class Other {
void m1() {
}
String m2() {
return "Hello";
}
int m3(int n) {
return n;
}
}
英文:
I have the below code. I want to execute m3()
in parallel by 3 threads as I am executing m1 and m2.
How can I achieve it. I am using Spring Boot and java 8. Is it possible to execute m3()
using executor service.
@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
}
}
Error is
> Local variable i defined in an enclosing scope must be final or
> effectively final
The methods are below
@Service
class Other {
void m1() {
}
String m2() {
return "Hello";
}
int m3(int n) {
return n;
}
}
答案1
得分: 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));
}
}
英文:
try this:
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));
}
}
答案2
得分: 1
在Java中,您无法在匿名内部类(包括lambda表达式)中使用非final变量。
- final变量是只实例化一次的变量。
- effectively-final变量是在初始化后其值不会再改变的变量。
一个可能的解决方法是使用IntStream.range
和IntStream.forEach
方法:
IntStream.range(0, 201).forEach(i -> {
executorService.submit(() -> other.m1());
executorService.submit(() -> other.m2());
executorService.submit(() -> other.m3(i));
});
英文:
In Java you cannot use non-final variables in anonymous inner classes, i.e. lambda expressions as well.
- A final variable is one which is instantiated only one time.
- An effectively-final variable is one who's value never changes after the initialization.
One possible workaround is using IntStream.range
and IntStream.forEach
methods:
IntStream.range(0, 201).forEach(i -> {
executorService.submit(() -> other.m1());
executorService.submit(() -> other.m2());
executorService.submit(() -> other.m3(i));
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论