【问题标题】:Endless loop with controlled exit带有受控退出的无限循环
【发布时间】:2017-06-14 07:54:04
【问题描述】:

我需要一个无限循环的批处理程序。在这个循环中,他正在做某事,然后等待 x 秒。现在的问题是,如何从程序外部停止循环?一种选择是读取文件并在 s.o. 时中断。在里面写了“STOP”,但是如果我总是打开和关闭文件,性能如何?

是否可以在同一运行时内启动第二个线程,例如将布尔“运行”设置为 false 或其他? 这是我的“停止文件”代码。

 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")));
        }

【问题讨论】:

    标签: java loops batch-processing exit


    【解决方案1】:

    我以前在 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);
            }
    
        }
    }
    

    【讨论】:

      【解决方案2】:

      目前我能想到的唯一方法是使用Socket 并让另一个单独的进程向您的客户发送操作。换句话说,您将拥有一个服务器-客户端连接。试试this tutorial

      【讨论】:

        【解决方案3】:

        比读取文件更简单的方法是,您可以使用exists() 来检查文件是否存在。

        File stopFile = new File(System.getProperty("StopFile"));
        
        while (!stopFile.exists()){
        

        当然,您可能希望在循环后删除此文件。

        stopFile.delete();
        

        【讨论】:

          【解决方案4】:

          我也提议像 Monoteq 提议的套接字。如果您不想使用套接字,我不会读取文件并扫描内容,而只是测试是否存在。这应该会提高性能。

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

          仍然不是最漂亮的解决方案,但比读取文件内容要好。

          【讨论】:

            猜你喜欢
            • 2015-11-07
            • 2016-11-07
            • 2020-06-06
            • 2017-01-20
            • 1970-01-01
            • 2012-06-28
            • 2019-06-16
            • 2020-10-31
            相关资源
            最近更新 更多