I made a code that each subprocess call is executed by a different Thread, but they execute the same method with same parameters.
Would you like to call these subprocesses using Thread but passing different commands?
Example, open the calculator and cmd, or different programs and etc.
Main Program Class:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public final class UsandoThreadComSubprocessos {
public void execute() {
ExecutorTask task = new ExecutorTask(); // Criando um objeto tipo ExecutorTask
Thread executorThread = new Thread(task); //Criando uma thread para executar o Executor
executorThread.start(); //Executando a Thread
}
public static void main(String[] args) {
new UsandoThreadComSubprocessos().execute();//Iniciando uma thread
new UsandoThreadComSubprocessos().execute();//Iniciando uma Segunda Thread
}
}
class ExecutorTask implements Runnable {
@Override
public void run() {
Process process = null; //Criando uma variavel tipo process
try {
process = Runtime.getRuntime().exec("cmd /c calc"); //Atribuindo um método que chama um subprocesso a uma variavel process
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); //Capturando o Retorno do processo solicitado
String line = "";
while ((line = reader.readLine()) != null) { //Lendo o retorno do processo atribuido a variavel line
System.out.println(line);// Mostrando o resultado na tela
}
process.waitFor(); //
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
return;
}
}
}