我目前正在构建一个小型的swing应用程序,用于格式化驱动器、更改权限以及执行一些其他小任务。
目前,我遇到了一个问题,运行多个进程会导致它们异步运行,这很棒,因为它可以让我快速调度大量进程,但是对于我正在做的事情来说,我需要进程等待前面的进程完成。
我遇到的问题是,process.waitFor()方法会延迟GUI(swing)无法执行任何操作,直到所有进程完成。
我目前正在使用以下代码结构(我从这里实现的答案中获得)来部署我的命令/进程。
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
class RunSynchronously{
private static final String sudoPassword = "1234";
public static void main(String[] args) {
Process process = null;
String[] firstCmd = {"/bin/bash", "-c", "echo " + sudoPassword + "| sudo -S chmod 777 -R /media/myuser/mydrive"};
try {
process = Runtime.getRuntime().exec(firstCmd);
} catch (IOException ex) {
Logger.getLogger(Wizard_Home.class.getName()).log(Level.SEVERE, null, ex);
}
try {
process.waitFor();
} catch (InterruptedException ex) {
Logger.getLogger(Wizard_Format.class.getName()).log(Level.SEVERE, null, ex);
}
String[] secondCmd = {"/bin/bash", "-c", "echo " + sudoPassword + "| sudo -S chmod 755 -R /media/myuser/mydrive"};
try {
process = Runtime.getRuntime().exec(secondCmd);
} catch (IOException ex) {
Logger.getLogger(Wizard_Home.class.getName()).log(Level.SEVERE, null, ex);
}
try {
process.waitFor();
} catch (InterruptedException ex) {
Logger.getLogger(Wizard_Format.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
如何在保持GUI活跃而不休眠/等待的情况下延迟进程或创建队列?