当我在Eclipse中用Java编写代码并第二次运行它时,第一个进程仍在运行。例如,当我写了一个带有一些输出的无限循环,运行它一次然后再次运行它时,它会从两个运行中打印输出,即第一次和第二次运行。此外,Eclipse变得缓慢。是否有一种方法可以在重新运行时自动终止第一个进程?
看起来你的程序没有退出。你可以在控制台视图的右上角使用小红方块结束该进程。
简短回答:
前往 Window -> Show View -> Debug, 选择你的程序并终止它。
详细解释:
根据你的问题描述,你可能在使用一个使用线程的框架(你的游戏中是否使用了Swing?)。你也可以在调试视图中看到正在运行的线程。
JVM会在所有用户线程执行完毕之前不会结束进程。
如果你正在使用Swing,你可以使用JFrame setDefaultCloseOperation更改窗口关闭的默认行为。
或者你可以使用System.exit(0)终止JVM进程。
共识似乎是这是不可能的。作为一个脚本编程背景的人,我习惯于进行大量的手动测试,并且我喜欢在几乎每次更改时编译程序。
以下类(Bomber)在10分钟后使System.exit(0)。只需将Bomb对象扔进Main中,Bomber daBomb = new Bomber();
并触发daBomb.reset();
以重置计时器。一旦进程像苍蝇一样聚集在窗台上,您可以单击控制台选项卡栏中的双X()来关闭所有死进程的控制台。
public class Bomber {
Bomb bomb = new Bomb();
public Bomber() throws InterruptedException {
Thread thread = new Thread(bomb);
thread.start();
}
public void reset() {
bomb.reset();
}
//kill because someone cut the redwire!
public void redWire() {
bomb.timer = 1000;
}
//Defuses bomb
public void greenWire() {
reset();
bomb.greenWire=false;
}
public class Bomb implements Runnable {
public int timer;
public boolean greenWire;
public Bomb() {
reset();
greenWire=true;
}
public void run() {
try {
while (timer > 1) {
Thread.sleep(1000L);
timer = timer - 1000;
//System.out.println(timer);
}
if (greenWire) {
System.exit(0); // kill, because no-one cut the green wire.
}
} catch (InterruptedException iex) {
}
}
public void reset() {
timer = 3000000; // five minutes
// timer = 5000; // Five seconds
}
}
}
你想要深入地整合轰炸机功能取决于你。我为 Main 创建了一个函数。请注意,以下内容可能不完美,因为我刚刚删除了许多非核心代码,并没有测试以确保它仍然可用。
public static void startUp() throws InterruptedException {
Bomber daBomb = new Bomber();
String input = "";
Interpreter console = new Interpreter();
while (!input.equalsIgnoreCase("quit")) {
daBomb.reset();
input = terminal.next().toLowerCase();
}
daBomb.redWire();
}