问题
I'm writing an app in java allowing me to run other applications. To do that, I've used an Process class object, but when I do, the app awaits the process to end before exiting itself. Is there a way to run external application in Java, but don't wait for it to finish?
public static void main(String[] args)
{
FastAppManager appManager = new FastAppManager();
appManager.startFastApp("notepad");
}
public void startFastApp(String name) throws IOException
{
Process process = new ProcessBuilder(name).start();
}
回答1:
ProcessBuilder.start() does not wait for process to finish. You need to call Process.waitFor() to get that behaviour.
I did a small test with this program
public static void main(String[] args) throws IOException, InterruptedException {
new ProcessBuilder("notepad").start();
}
When run in netbeans it appear to be still running. When running from command line with java -jar it returns immediately.
So your program is probably not waiting to exit, but your IDE makes it seem so.
回答2:
You can run it in another thread.
public static void main(String[] args) {
FastAppManager appManager = new FastAppManager();
appManager.startFastApp("notepad");
}
public void startFastApp(final String name) throws IOException {
ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.submit(new Runnable() {
@Override
public void run() {
try {
Process process = new ProcessBuilder(name).start();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
You might want to start a daemon thread depending on your needs:
ExecutorService executorService = Executors.newSingleThreadExecutor(new ThreadFactory() {
@Override
public Thread newThread(Runnable runnable) {
Thread thread = new Thread();
thread.setDaemon(true);
return thread;
}
});
来源:https://stackoverflow.com/questions/9624385/run-a-external-application-in-java-but-dont-wait-for-it-to-finish