2013-06-26 27 views
2

所以,我有一個無限循環中,像這樣我的控制檯應用程序的主線程中運行。Java控制檯應用程序:從無限循環接受命令

public static void main(String[] args) { 
    while(true){ 
     doSomething(); 
     doSomethingElse(); 
     System.out.println("some debugging info"); 
     doAnotherThing(); 
    } 
} 

我希望這段代碼能反覆運行。

偶爾,我想輸入一個命令到控制檯,比如字符串「give me more info plox」,然後如果該命令等於某事,我希望我的代碼執行某些操作。

通常情況下,我只想用掃描儀,但我不能這樣做,在這裏 - 因爲scanner.next();暫停我的代碼...我希望我的代碼能夠繼續運行,不管我是否輸入命令。我能看到的唯一解決方法是使用文件。但是還有其他的選擇嗎?

+1

提示:你不想無限重複這個事情,你只是希望它要等到事情發生。 – sashkello

回答

2

使用線程,主線程從控制檯,另一個做循環讀取,第一個線程更新字符串(製片人)和循環線程讀取列表中的一個列表,查看是否有它新的東西(消費者)

+0

TY!作品。我沒有意識到我可以這樣做:D – Leisure

0

你可以嘗試System.in.available(),它是非阻塞的。然而,這種方法被認爲是沒有很好的spec'ed。在某些系統上(基於Unix的OpenJDK),只有當用戶使用enter密鑰確認輸入後,纔會返回> 0

否則,莫爾加諾的建議,不斷爲System.in.read()阻止在一個單獨的線程。

2

你可以做一些類似下面

public class MainApp implements Runnable 
{ 

    static String command; 
    static boolean newCommand = false; 

    /** 
    * @param args the command line arguments 
    */ 
    public static void main(String[] args) 
    { 
     MainApp reader = new MainApp(); 
     Thread t = new Thread(reader); 
     t.start(); 

     while (true) 
     { 
      doSomething(); 

      if (newCommand) 
      { 
       System.out.println("command: " + command); 
       newCommand = false; 
       //compare command here and do something 
      } 
     } 
    } 

    private static void doSomething() 
    { 
     try 
     { 
      System.out.println("going to do some work"); 
      Thread.sleep(2000); 
     } catch (InterruptedException ex) 
     { 
      Logger.getLogger(MainApp.class.getName()).log(Level.SEVERE, null, ex); 
     } 
    } 

    @Override 
    public void run() 
    { 
     Scanner scanner = new Scanner(System.in); 

     while(true) 
     { 
      command = scanner.nextLine(); 
      System.out.println("Input: " + command); 
      newCommand= true; 
     } 
    } 



} 
相關問題