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

标签 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
    }
}
错误是

Local variable i defined in an enclosing scope must be final or effectively final


方法如下
@Service
class Other {
    void m1() {
    }
    
    String m2() {
        return "Hello";
    }
 
    int m3(int n) {
        return n;
    }
}

最佳答案

在Java中,您不能在匿名内部类(即lambda表达式)中使用非最终变量。

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

  • 一种可能的解决方法是使用IntStream.rangeIntStream.forEach方法:
    IntStream.range(0, 201).forEach(i -> {
        executorService.submit(() -> other.m1());
        executorService.submit(() -> other.m2());
        executorService.submit(() -> other.m3(i));
    });
    

    关于java - 带有返回类型和输入参数的Execute方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64027507/

    相关文章:

    c# - 暂停方法设置 # of milliseconds

    java - 让 adMob 为 Android 旧版本运行

    java - 客户端服务器程序字符串泄漏?

    java - Spring Boot 2.0.0.RELEASE迁移后"Got different size of tuples and aliases"异常

    Spring 确实存在时找不到 bean xml 配置文件

    java - 模拟 java.lang.Thread 的最佳方法是什么?

    Python ThreadPoolExecutor 线程未完成

    java - 长期存储 JTable 数据的好方法?

    java - 使用 GridLayout 时如何将组件的大小锁定在可调整大小的框架中?

    sql-server - Spring 批处理 : efficient way to query results of a stored procedure within a tasklet