2017-06-14 35 views
2

我需要一個無限循環的批處理程序。在這個循環中,他正在做一些事情,然後等待X秒。現在的問題是,我怎樣才能阻止程序之外的循環?一個選項是讀取一個文件,如果s.o中斷,在內部寫道「停止」,但如果我總是打開和關閉文件,它的表現如何?無盡循環與控制出口

難道不可能在同一運行時間內啓動第二個線程,例如:將布爾運行設置爲false或其他東西? 這是我的代碼「stop-file」。

Integer endurance = args[3] != null ? new Integer(args[3]) : new Integer(System.getProperty("endurance")); 
BufferedReader stop = new BufferedReader(new FileReader(args[4] != null ? args[4] : System.getProperty("StopFile"))); 
     while (!stop.readLine().toUpperCase().equals("STOP")) 
     { 
      doSomething(args); 
      try { 
       Thread.sleep(endurance); 
      } catch (InterruptedException e) { 
       e.printStackTrace(); 
       System.exit(12); 
      } 
      stop.close(); 
      stop = new BufferedReader(new FileReader(args[4] != null ? args[4] : System.getProperty("StopFile"))); 
     } 

回答

0

我之前在Android中做過這樣的操作。我在子線程中啓動了邏輯並從父線程發送了中斷信號。示例代碼有點像下面。

class TestInterruptingThread1 extends Thread 
{ 
    public void run() 
    { 
     try 
     { 
      //doBatchLogicInLoop(); 
     } 
     catch (InterruptedException e) 
     { 
      throw new RuntimeException("Thread interrupted..." + e); 
     } 

    } 

    public static void main(String args[]) 
    { 
     TestInterruptingThread1 t1 = new TestInterruptingThread1(); 
     t1.start(); 
     boolean stopFlag = false; 
     try 
     { 
      while (stopFlag == false) 
      { 
       Thread.sleep(1000); 
       //stopFlag = readFromFile(); 
      } 
      t1.interrupt(); 
     } 
     catch (Exception e) 
     { 
      System.out.println("Exception handled " + e); 
     } 

    } 
} 
0

我可以在那一刻想到的唯一方法是使用一個Socket,並有另一個單獨的進程發送動作到客戶端。換句話說,你將有一個服務器 - 客戶端連接。嘗試this tutorial

0

比讀取文件更簡單的方法,您可以檢查文件是否存在exists()

File stopFile = new File(System.getProperty("StopFile")); 

while (!stopFile.exists()){ 

當然,你可能想在你的循環後刪除這個文件。

stopFile.delete(); 
0

我也建議像Monoteq這樣的套接字提出。如果你不想使用套接字,我不會讀取文件並掃描內容,而只是測試是否存在。這應該會提高性能。

File f; 
while((f= new File(args[4] != null ? args[4] : System.getProperty("StopFile"))).exists()) { 
    doSomething(); 
} 
f.delete(); 

仍然不是最美麗的解決方案,但比閱讀文件的內容更好。