【问题标题】:How to synchronize java code如何同步java代码
【发布时间】:2011-02-03 07:18:21
【问题描述】:

我有下一个代码:

Process p = Runtime.getRuntime().exec(args);

我希望我的程序等待 Runtime.getRuntime().exec(args);完成导致它持续 2-3 秒,然后继续。

想法?

【问题讨论】:

    标签: java runtime synchronize


    【解决方案1】:

    使用Process.waitFor():

    Process p = Runtime.getRuntime().exec(args);
    int status = p.waitFor();
    

    来自 JavaDoc:

    使当前线程在必要时等待,直到此 Process 对象表示的进程终止。如果子进程已经终止,则此方法立即返回。如果子进程尚未终止,则调用线程将被阻塞,直到子进程退出。

    【讨论】:

    • 工作得很好。谢谢。非常类似于用于线程池的awaitTermination()
    【解决方案2】:

    这是一个示例代码:

    Process proc = Runtime.getRuntime().exec(ANonJava.exe@);
    InputStream in = proc.getInputStream();
    byte buff[] = new byte[1024];
    int cbRead;
    
    try {
        while ((cbRead = in.read(buff)) != -1) {
            // Use the output of the process...
        }
    } catch (IOException e) {
        // Insert code to handle exceptions that occur
        // when reading the process output
    }
    
    // No more output was available from the process, so...
    
    // Ensure that the process completes
    try {
        proc.waitFor();
    } catch (InterruptedException) {
        // Handle exception that could occur when waiting
        // for a spawned process to terminate
    }
    
    // Then examine the process exit code
    if (proc.exitValue() == 1) {
        // Use the exit value...
    }
    

    您可以在此网站上找到更多信息:http://docs.rinet.ru/JWP/ch14.htm

    【讨论】:

    • 是的,你的工作正常。谢谢!是否可以同步。如果我不想使用 Runtime.getRuntime().exec(args) 但 WsImport.doMain(args);
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多