我想知道在用户决定停止之前永远运行脚本的最佳方法是什么?我应该运行一个小gui,还是在eclipse中有一个循环开始/停止按钮来执行此操作?
或者Java程序中有没有办法停止简单的用户输入,比如键盘上的键序列?
没有找到任何能够通过大量搜索来解决这个问题的事情,所以对任何想法都会感激不尽。
答案 0 :(得分:0)
您可以尝试以下方式:
Thread
来监听System.in
:class ShutdownListener implements Runnable {
private boolean running = false;
private boolean exit = false;
@Override
public void run() {
running = true;
Scanner sc = new Scanner(System.in);
System.out.print("Type any number to exit the program : ");
sc.nextInt();
exit = true;
}
public boolean isRunning() {
return running;
}
public boolean shouldExit() {
return exit;
}
}
main
方法中,启动Listener
如果它尚未凝视,则在每次迭代中检查exit
布尔值的状态是否发生变化。public static void main(String[] args) {
try {
ShutdownListener shutdownListener = new ShutdownListener();
while(true) {
//do something here forever...
Thread.sleep(1000);
if(!shutdownListener.isRunning()) {
new Thread(shutdownListener).start();
}else if(shutdownListener.shouldExit()) {
throw new InterruptedException();
}
}
} catch (InterruptedException e) {
System.out.println("Program is shutting down");
}
}
此program
将一直运行,直到您决定将其关闭为止。
输出:
Type any number to exit the program : 1
Program is shutting down
Process finished with exit code 0