简体   繁体   English

在继续进行之前,如何等待方法完全完成?

[英]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. 下面的代码将在killProcess()杀死它之后运行OSK(屏幕键盘)进程,以前在我添加Thread.sleep 1秒钟之前它不会弹出。 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?? 那么,有什么方法可以确保killProcess()在没有Thread.sleep的情况下启动OSK进程一秒钟之前完全执行? something that is not timed-based, a code that will run killProcess() completely before going into the next line. 并非基于时间的东西,它的代码将在进入下一行之前完全运行killProcess()。 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. Runtime.exec(String)返回一个Process ,它具有waitFor()方法。 This will block the current Thread until the process has terminated. 这将阻塞当前线程,直到进程终止。

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

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