简体   繁体   中英

How to wait for a method to finish completely before proceeding?

the coding below will run OSK (On Screen Keyboard) process after killProcess() kills it, previously it does not pop up before I added the Thread.sleep for 1 second. So is there any way that I can make sure killProcess() is fully executed before it start the OSK process without Thread.sleep for one second?? something that is not timed-based, a code that will run killProcess() completely before going into the next line. Sorry for any confusion and thanks for reading! Hope someone is willing to help me with this one.

public static void main(String... args) {
    try {
        killProcess();

        try {
            Thread.sleep(1000);
        } catch (InterruptedException ex) {
            Thread.currentThread().interrupt();
        }

        Runtime.getRuntime().exec("c:\\Temp\\osk.exe");

    } catch (Exception ex) {
        ex.printStackTrace();
    }

}

public static void killProcess() throws Exception {

    Runtime rt = Runtime.getRuntime();

    rt.exec("cmd.exe /c taskkill " + "osk.exe");

    Runtime.getRuntime().exec("taskkill /IM " + "osk.exe");

}
public static void main(String... args) {
    try {
        killProcess();
        Runtime.getRuntime().exec("c:\\Temp\\osk.exe");

    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

public static void killProcess() throws Exception {
    Runtime rt = Runtime.getRuntime();
    rt.exec("cmd.exe /c taskkill " + "osk.exe").waitFor();
    rt.exec("taskkill /IM " + "osk.exe").waitFor();
}

Runtime.exec(String) returns a Process , which has the waitFor() method. This will block the current Thread until the process has terminated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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