How to execute external commands using multithreading in Java?

I want to run external programs that are repeated N times, each time waiting for the output and processing it. Since it is too slow to work consistently, I have tried multithreading. The code is as follows:

public class ThreadsGen {

public static void main(String[] pArgs) throws Exception {
    for (int i =0;i < N ; i++ )
    {
        new TestThread().start();
    }   
}

static class TestThread extends Thread {

public void run() {
        String cmd = "programX";
        String arg = "exArgs"; 

        Process pr;
        try {
            pr = new ProcessBuilder(cmd,arg).start();

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

        try {
            pr.waitFor();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        //process output files from programX.
        //...
}

However, it seems to me that only one thread is executed at a time (by checking CPU usage).
What I want to do is get all the threads (except for those that are waiting for the program to finish)? What is wrong with my code?

Is it because it pr.waitFor();makes the main thread wait on each subflow?

+3
source share
2 answers

waitFor() ( , , , Threads).

, Java . , (), , , .

, , Java- , . ( ps - ).

+1

All Articles