Java run async processes

前端 未结 3 805
野趣味
野趣味 2020-12-19 05:10

I am trying to run an async process and I do not want the program to wait until the end of these processes executions. I found this question how to run shell script asynchro

相关标签:
3条回答
  • 2020-12-19 05:53

    You are reading the output streams of your process, and thats the reason your java program does not exit:

            printStream(process.getErrorStream(), true);
            printStream(process.getInputStream(), true);
    

    Your stream reading will keep blocking your code.

    You may like to redirect output of your launched process to a log file and read that later.

    0 讨论(0)
  • 2020-12-19 05:57

    You need to make your thread a daemon thread. Use setDaemon(true) before starting it.

     commandLineThread.setDaemon(true);
    

    A daemon thread is a thread that does not prevent the JVM from exiting. See this question: What is Daemon thread in Java? for more information about daemon threads.

    Edit:

    By judging from your comments you need the command to run even though the JVM is about to exit. I assume the command variable contains the script you want to run? You could make two changes to make the program behave as I think you want.

    1. Start bash with -c to execute your command, then you do not have to send things to an output stream.
    2. Start the process before starting your thread that waits for the output.

    The resulting code would look something like:

    public void runCommandLine(String directory) throws IOException {
        ProcessBuilder processBuilder = new ProcessBuilder(
                        "/bin/bash -c " + command);
        processBuilder.directory(new File(directory));
        Process process = processBuilder.start();
        Thread commandLineThread = new Thread(() -> {
            try {
                printStream(process.getErrorStream(), true);
                printStream(process.getInputStream(), true);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        });
        commandLineThread.setDaemon(true);
        commandLineThread.start();
        System.out.println("Task Dispatched");
    }
    
    0 讨论(0)
  • 2020-12-19 05:59
               Thread commandLineThread = new Thread(() -> {
                try {
                    BufferedReader br=new BufferedReader(
                            new InputStreamReader(
                                    process.getInputStream()));
                    String line;
    
                    while((line=br.readLine())!=null){
                        System.out.println(line);
                    }
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            });
            commandLineThread.setDaemon(true);
            commandLineThread.start();
    
    0 讨论(0)
提交回复
热议问题