1

I want to have a main class in which users define how many Customer class processes they want to start. How do i solve this in my main? Below is the code I use to run Customer class once.

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
  • A for loop should do the trick. Commented Dec 16, 2018 at 18:12

1 Answer 1

2

Method 1, cloning

I don't know how good idea it is but, you could try doing something like this:

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

The .clone() will make a copy of it and then start the process from it. Now you can do:

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(); 

Method 2, array of arguments

Also you could store your arguments in an array and every time you want to start new Process, you would just create a new instance of ProcessBuilder, like so:

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(); } 

And like this, if you need to store created 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(); } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.