我想要一个主类,用户可以在其中定义他们想要启动的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,克隆
我不知道这个主意有多好,但是,你可以试着做这样的事情:
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();
}