Help with Subprocess and Thread

Asked

Viewed 103 times

0

I made a code that each subprocess call is executed by a different Thread, but they execute the same method with same parameters.

You could call these subprocesses using Thread but passing different commands?

Example, open the calculator and cmd, or different programs and etc.

Main Class of the Program:

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

1 answer

0

You can put a parameter in your Runnable constructor (Executortask);

class ExecutorTask implements Runnable {
    String comando;

ExecutorTask(String comando) {
    this.comando = comando;
}

@Override
public void run() {
    Process process = null; //Criando uma variavel tipo process

    try {

        process = Runtime.getRuntime().exec("cmd /c " + comando); //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;
    }
}

}

  • Right, I’ll implement it here .

Browser other questions tagged

You are not signed in. Login or sign up in order to post.