简体   繁体   English

一段时间后加入Java中的线程/进程-Java

[英]Joining a thread / process in Java after some time - Java

I have the following method, which executes a command as a process and returns the ouput: 我有以下方法,该方法将命令作为进程执行并返回输出:

public String execute(String command) {
        StringBuffer output = new StringBuffer();
        Process p;
        try {
            p = Runtime.getRuntime().exec(command);
            BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line = "";
            while ((line = reader.readLine()) != null) {
                output.append(line + "\n");
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return output.toString();
    }

This code is great whenever the command returns, however for continuing running processes such as top this may never return. 每当命令返回时,此代码就很棒,但是对于持续运行的进程(例如top可能永远不会返回。 The code does not need to keep running continuously. 该代码不需要保持连续运行。 It only needs to capture a snapshot, or it could time out after some time, such as 3 seconds. 它仅需要捕获快照,否则可能会在一段时间(例如3秒)后超时。 How can I accomplish that? 我该怎么做?

Process has a method waitFor . Process有一个方法waitFor It can be used to force a timeout. 可用于强制超时。 For example: 例如:

if ((p = Runtime.getRuntime().exec(execPath)) != null) && !p.waitFor(TIMEOUT_CONSTANT, TimeUnit.SECONDS)) {
    p.destroyForcibly();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM