我想拥有一个主类,用户可以在其中定义要启动多少个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();
}
答案 0 :(得分:2)
我不知道这是一个好主意,但是,您可以尝试执行以下操作:
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();
您还可以将参数存储在数组中,并且每次您要启动新的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();
}