如何按下按钮,停止内部程序运行?

(来自IDE风格程序运行的个别问题)

您最好的选择可能是通过ProcessBuilder分叉一个新的JVM。

但是,可以使用ThreadGroups终止内部程序(以及它产生的所有线程)。 (我不推荐它。它使用了根据docs的“ 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... 
  1. 在单独的JVM中运行代码。 使用调试器接口来控制该JVM。
  2. 检测您要运行的类的字节代码。 在适当的位置插入取消检查,以及捕获对全局JVM资源的访问。

第二种选择可能是烦人的臭虫的无穷无尽的来源。