Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/369.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用返回类型和输入参数并行执行方法_Java_Spring_Multithreading_Spring Boot_Parallel Processing - Fatal编程技术网

Java 使用返回类型和输入参数并行执行方法

Java 使用返回类型和输入参数并行执行方法,java,spring,multithreading,spring-boot,parallel-processing,Java,Spring,Multithreading,Spring Boot,Parallel Processing,我有下面的代码。在执行m1和m2时,我希望通过3个线程并行执行m3() 我怎样才能做到这一点。我正在使用SpringBoot和Java8。是否可以使用executor服务执行m3() @Service class Main { @Autowired Private Other other; ExecutorService executorService = Executors.newFixedThreadPool(3); void test_method(

我有下面的代码。在执行m1和m2时,我希望通过3个线程并行执行
m3()

我怎样才能做到这一点。我正在使用SpringBoot和Java8。是否可以使用executor服务执行
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
    }
}
试试这个:

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));        
    }
}
void test_method(){
对于(int i=0;i<201;i++){
executorService.submit(其他::m1);
执行服务提交(其他::m2);
最终int i1=i;
executorService.submit(()->other.m3(i1));
}
}

在Java中,您不能在匿名内部类中使用非final变量,即lambda表达式

  • 最后一个变量是只实例化一次的变量
  • 一个有效的最终变量是在初始化后其值不会改变的变量
一种可能的解决方法是使用
IntStream.range
IntStream.forEach
方法:

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

错误是什么?
我在封闭范围中定义的局部变量必须是final或有效final
我将尝试,谢谢。我通过为int
final MyContainer MyContainer=new MyContainer(i)创建一个容器类解决了这个问题;myContainer.getIntValue()
。但是您有没有什么优雅的解决方案可以在不使用ExecutorService的情况下与ot并行执行m3(),而且您和我的解决方案几乎相同。但是假设我将某个自定义Pojo类传递给m3@PaleBlueDot与什么并行执行m3()?它已经以最大可能的逻辑并行性执行。要实现最大的物理并行性,请使用ExecutorService ExecutorService=Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());谢谢。但是你的方法对int有效。假设我将一些自定义Pojo(如MyObject)传递给m3(),那么我将如何做?有什么优雅的方法吗?Enchanted循环工作:
for(Pojo Pojo:list){executorService.submit(()->other.m3(Pojo));}
IntStream.range(0, 201).forEach(i -> {
    executorService.submit(() -> other.m1());
    executorService.submit(() -> other.m2());
    executorService.submit(() -> other.m3(i));
});