简体   繁体   English

等到被调用的jar执行完成

[英]Wait until called jar execution finished

In my Java program, I start an external .jar file which modifies the system clipboard content. 在我的Java程序中,我启动了一个外部.jar文件,该文件修改了系统剪贴板的内容。 After that I continue with the data written to the clipboard. 之后,我继续将数据写入剪贴板。 Unfortunately it looks like the jar gets started and the program doesn't wait until the jar execution is finished. 不幸的是,它看起来像jar一样启动,并且程序不会等到jar执行完成。

Here is the code I use to start the jar file: 这是我用来启动jar文件的代码:

import java.io.IOException;

public class JarExecutor {

    private String pathToJar = "";
    private String jarFile = "";
    private String pathToJava = "C:\\ProgramData\\Oracle\\Java\\javapath\\javaw.exe";

    public JarExecutor(String pathToJar, String jarFile) {
        this.pathToJar = pathToJar;
        this.jarFile = jarFile;
    }

    public void execute() {

        ProcessBuilder pb = new ProcessBuilder(pathToJava, "-jar", pathToJar + jarFile);
        try {
            Process p = pb.start();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

And that's from the main program: 那是来自主程序的:

public static void main(String[] args) {
        String pathToJar = "\\\\some\\net\path";
        String jarFile = "externalProgram.jar";

        JarExecutor myExecutor = new JarExecutor(pathToJar, jarFile)
        myExecutor.execute();

        [...]
}

As long as I put a Thread.sleep(ms) with ms > 3000 after the myExecutor.execute() in my program it works, but I guess that's no proper way to wait for the other process to be finished. 只要我在程序中的myExecutor.execute()之后放置一个ms> 3000的Thread.sleep(ms) ,它就可以工作,但是我想这不是等待其他进程完成的正确方法。

Right there in the Process documentation : Process文档中

waitFor

 public abstract int waitFor() throws InterruptedException 

Causes the current thread to wait, if necessary, until the process represented by this Process object has terminated. 如有必要,使当前线程等待,直到此Process对象表示的进程终止。 This method returns immediately if the subprocess has already terminated. 如果子进程已经终止,则此方法立即返回。 If the subprocess has not yet terminated, the calling thread will be blocked until the subprocess exits. 如果子进程尚未终止,则调用线程将被阻塞,直到子进程退出。

Using waitFor would be the perfect solution if you need the main to proceed only after the jar execution is done. 如果只需要在jar执行完成后继续执行main ,则使用waitFor将是一个完美的解决方案。 Otherwise, you will be looking at some sort of interprocess communication. 否则,您将研究某种进程间通信。 Try using sockets to pass messages between the processes. 尝试使用套接字在进程之间传递消息。

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

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