繁体   English   中英

并行执行具有返回类型和输入参数的方法

[英]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.rangeIntStream.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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM