使用ProcessBuilder

时间:2018-12-16 18:11:01

标签: java multiprocessing processbuilder multiprocess

我想拥有一个主类,用户可以在其中定义要启动多少个Customer类过程。我该如何解决这个问题?下面是我用来运行一次Customer类的代码。

try {       
        ProcessBuilder customer = new ProcessBuilder("java.exe","-cp","bin","lab_3.Customer");
        Process runCustomer = customer.start();

        runCustomer.waitFor();

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

1 个答案:

答案 0 :(得分:2)

方法1,克隆

我不知道这是一个好主意,但是,您可以尝试执行以下操作:

ProcessBuilder customer = new ProcessBuilder("java.exe","-cp","bin","lab_3.Customer");
Process runCustomer = customer.clone().start();

.clone()将对其进行复制,然后从中开始该过程。现在您可以执行以下操作:

ProcessBuilder customer = new ProcessBuilder("java.exe","-cp","bin","lab_3.Customer");
Process runCustomer1 = customer.clone().start();
Process runCustomer2 = customer.clone().start();
Process runCustomer3 = customer.clone().start();
Process runCustomer4 = customer.clone().start();

方法2,参数数组

您还可以将参数存储在数组中,并且每次您要启动新的Process时,只需创建一个ProcessBuilder的新实例,就像这样:

String command = "java.exe";
String[] args = new String[]{ "-cp", "bin", "lab_3.Customer" };

for(int i = 0; i < numOfProcesses; i++) {
     new ProcessBuilder(command, args).start();
}

这样,如果您需要存储创建的Processes

String command = "java.exe";
String[] args = new String[]{ "-cp", "bin", "lab_3.Customer" };
Process[] processes = new Process[numOfProcesses];

for(int i = 0; i < numOfProcesses; i++) {
     processes[i] = new ProcessBuilder(command, args).start();
}