[英]How do I make a button that, when pressed, stops an internal program from running?
最好的选择可能是通过ProcessBuilder
派生新的JVM。
但是,可以使用ThreadGroups杀死内部程序(及其产生的所有线程)。 (尽管我不建议这样做。它使用stop
方法,根据文档, 此方法是 “ 不建议使用 。此方法本质上是不安全的。有关详细信息,请参见Thread.stop()。 ”):
public class Main {
public static void main(String args[]) throws InterruptedException {
ThreadGroup internalTG = new ThreadGroup("internal");
Thread otherProcess = new Thread(internalTG, "Internal Program") {
public void run() {
OtherProgram.main(new String[0]);
}
};
System.out.println("Starting internal program...");
otherProcess.start();
Thread.sleep(1000);
System.out.println("Killing internal program...");
internalTG.stop();
}
}
class OtherProgram {
public static void main(String[] arg) {
for (int i = 0; i < 5; i++)
new Thread() {
public void run() {
System.out.println("Starting...");
try {
sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Stopping...");
}
}.start();
}
}
输出:
Starting internal program...
Starting...
Starting...
Starting...
Starting...
Starting...
Killing internal program...
第二种选择可能是烦人的bug的源源不断。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.