如何使用java 8 Streams同时或并行运行3个方法

时间:2017-09-05 12:31:11

标签: java parallel-processing java-8

1)热衷于知道如何使用Java 8并行运行Method1,2,3

2)使用流来满足我对Java 8的要求是否正确?

public void RunParallel()
{
    String method1 = method1();
    String method2 = method2();
    String method3 = method3(String Value);
}

Stream.<Runnable>of(() -> method1(),() -> method2(),() -> method3()).parallel().forEach(Runnable::run);

3 个答案:

答案 0 :(得分:3)

您可以使用Java 8执行以下操作,使用以下代码方法1,方法2&amp; method3并行运行。如果您想在完成所有操作后执行某些操作,则可以使用future.get();

public void RunParallel()
{
    CompletableFuture<Void> future1 = CompletableFuture.runAsync(()->{
        String method1 = method1();
    });

    CompletableFuture<Void> future2 = CompletableFuture.runAsync(()->{
        String method2 = method2();
    });

    CompletableFuture<Void> future3 = CompletableFuture.runAsync(()->{
        String method3 = method3("some inp");
    });

    CompletableFuture<Void> future = CompletableFuture.allOf(future1, future2, future3); 
    try {
        future.get(); // this line waits for all to be completed
    } catch (InterruptedException  | ExecutionException e) {
        // Handle
    }
}

答案 1 :(得分:0)

为要并行运行的每个不同方法创建扩展线程的类,如下所示:

public static void main(String[] args) {
    new Operation1().start();
    new Operation2().start();
    ...
}

public class Operation1 extends Thread{
    public Operation1() {
        super("Operation1");
    }
    @Override
    public void run() {
        method1();
    }
}
public class Operation2 extends Thread{
...
}

答案 2 :(得分:0)

并行运行方法的非常简单的方法

Thread thread1=new Thread() {
   public void run() {
       method1();
   }
};
thread1.start();

对剩下的所有方法重复此操作。

以下是您的示例代码。这里是所有三个线程,并行执行相应的方法。

public class ThreadTest1 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Thread thread1 = new Thread() {
            public void run() {
                method1();
            }
        };
        thread1.start();

        Thread thread2 = new Thread() {
            public void run() {
                method2();
            }
        };
        thread2.start();

        Thread thread3 = new Thread() {
            public void run() {
                method3();
            }
        };
        thread3.start();

    }

    static void method1() {

        try {
            while(true){
            System.out.println("test1");
            Thread.currentThread().sleep(1000);
            }
        } catch (InterruptedException e) {
        }
    }

    static void method2() {
        try {
            while(true){
            System.out.println("test2");
            Thread.currentThread().sleep(1000);
            }
        } catch (InterruptedException e) {
        }
    }

    static void method3() {
        try {
            while(true){
            System.out.println("test3");
            Thread.currentThread().sleep(1000);
            }
        } catch (InterruptedException e) {
        }
    }

}