2017-06-14 65 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(); 

仍然不是最美丽的解决方案,但比阅读文件的内容更好。