Andrija Župić
Andrija Župić

Reputation: 19

Run multiple processes of a same class using ProcessBuilder

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

Upvotes: 1

Views: 1504

Answers (1)

rainisr
rainisr

Reputation: 304

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

Upvotes: 2

Related Questions