[英]Kill Process in Java programmatically
I have a Swing application which get inputs through the text boxes and when Start button is Hit/clicked, we start a Ant script - programmatically (org.apache.tools.ant.Project, org.apache.tools.ant.ProjectHelper) (ant file properties come from input text boxes). 我有一个Swing应用程序,该应用程序通过文本框获取输入,并且当单击“开始”按钮时,我们以编程方式(Aorg.apache.tools.ant.Project,org.apache.tools.ant.ProjectHelper)启动了一个Ant脚本( ant文件属性来自输入文本框)。 This Ant script will start checking out code from CVS.
这个Ant脚本将开始从CVS中检出代码。
Now, I want to stop this Ant script execution when user hits Stop button. 现在,我想在用户单击“停止”按钮时停止执行此Ant脚本。
Problem: As soon as user fills in text boxes and hits Start, I start the Ant script execution. 问题:用户填写文本框并单击“开始”后,便立即开始执行Ant脚本。 So, the control moves from that Applet or Input page to back end java code.
因此,控件从该Applet或Input页面移至后端Java代码。 So I am not able to access "Stop" button in main applet.
因此,我无法访问主小程序中的“停止”按钮。
我不确定,但是听起来您想要做的是使用线程执行后端Java代码,然后告诉该线程在用户按下stop时终止。
public class Kill
{
public static void main(String[] args) throws Exception
{
ProcessBuilder p = new ProcessBuilder("notepad.exe","fake.xml");
p.directory(new File("c:/temp/"));
System.out.println("Starting ...");
Process x = p.start();
System.out.println("Started ...");
System.out.println("Sleeping ...");
Thread.sleep(3000);
System.out.println("Woke up ...");
System.out.println("Destroying...");
x.destroy();
x.waitFor(); // If you don't wait for it then the application will be terminated as soon as it is started
System.out.println("Return value = " + x.exitValue());
System.out.println("Over ...");
}
}
One way is to use x.waitFor();
一种方法是使用
x.waitFor();
method and keep waiting for either user action to kill the ant process or it may finishes by its own. 方法,并一直等待用户采取行动杀死蚂蚁进程,否则它可能会自行完成。 Anyhow you will need the
x.destroy();
无论如何,您将需要
x.destroy();
and check for the success and failure using the x.exitValue()
. 并使用
x.exitValue()
检查成功与失败。 But using this in a worker thread makes more sense as the UI will remain responsive. 但是在工作线程中使用它更有意义,因为UI将保持响应状态。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.