带有返回类型和输入参数的Execute方法

时间:2020-09-23 12:01:31

标签: java spring multithreading spring-boot parallel-processing

我有以下代码。我想在执行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;
    }
}

2 个答案:

答案 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表达式)中使用非最终变量。

  • final 变量是仅实例化一次的变量。
  • 一个有效的 final 变量是在初始化后永远不变的值。

一种可能的解决方法是使用IntStream.rangeIntStream.forEach方法:

IntStream.range(0, 201).forEach(i -> {
    executorService.submit(() -> other.m1());
    executorService.submit(() -> other.m2());
    executorService.submit(() -> other.m3(i));
});