2017-03-04 48 views
-1

我想知道什么是最好的方式是永远运行一个脚本,直到用户决定停止?我应该运行一个小鬼,还是在Eclipse中有一个循环启动/停止按钮,这是否?保持进程运行直到用户退出?

还是有没有在Java程序停止简单的用户输入,如键盘上的按键序列?

没有找到任何解决这个问题的一堆搜索,所以会感激任何想法。

+0

你的程序在它完成一个单独的处理单元中运行或用户按下红色“停止”按钮。如果您使用无限循环,则只需使用停止按钮即可终止进程。 – Robert

回答

0

你可以尝试这样的:

  1. 创建一个单独的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 
    
    +0

    对不起,如果这听起来很明显,但我想知道如何在Eclipse中将其设置为true?我只需进入并将其更改为true,然后按顶部的绿色按钮(再次启动脚本)? –

    +0

    您可以创建一个单独的'Thread'来监听'System.in'或者从外部检索'File'。 –

    +0

    @Ke我编辑了帖子! –

    相关问题