Java ProcessBuilder启动多个java进程

时间:2014-12-11 13:28:42

标签: java multiprocessing processbuilder

在给定相同的Main.class,参数和VM选项的情况下,我可以生成多个不同的JVM吗? 可以使用ProcessBuilder吗?

1 个答案:

答案 0 :(得分:2)

以下是使用Process启动10个不同JVM进程的基本示例:

   for (int i = 0; i < 10; i++) {
            new Thread(new Runnable() {

                public void run() {
                    try {
                        //start a new jvm with 256m of memory with the MyClass passing 2 parameters
                        String cmd = "java -Xmx256M -cp myjar.jar com.mymainclass.MyClass par1 par2";
                        Process p = Runtime.getRuntime().exec(cmd);
                        BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
                        String line = br.readLine();
                        while (line != null) {
                            line = br.readLine();
                        }
                        br = new BufferedReader(new InputStreamReader(p.getErrorStream()));
                        line = br.readLine();
                        while (line != null) {
                            line = br.readLine();
                        }
                    } catch (IOException e) {
                    }

                }
            }).start();
        }