2

就我而言,我有三个不同类的三种方法。第一个是通过运行 jar 文件连续运行服务,第二个是检查是否有任何服务关闭,如果没有关闭则让它停止,如果有任何服务关闭,则通过运行 jar 文件运行服务,第三个是插入日志在数据库和文本文件中。

我已经这样做了,但它不能正常工作。

Thread thread1 = new Thread() {
   public void run() {
      Runjar.Runservices();
   }
};
Thread thread2 = new Thread() {
   public void run() {
      ControllerApplication.linuxCmd();
   }
};
Thread thread3 = new Thread() {
   public void run() {
      Utils.insertLog();
   }
};
thread1.start();
thread2.start();
thread3.start();

我如何以简单有效的方式在java中处理它。示例代码示例更受欢迎。提前致谢。

4

1 回答 1

2

如果您想在循环中连续调用所有这些方法,那么只需将您的代码更改为以下内容:

volatile boolean runServices = true;
volatile boolean linuxCmd = true;
volatile boolean insertLog = true;
int SLEEP_TIME = 100;//Configurable. 
Thread thread1 = new Thread() {
   public void run() {
       while (runServices)
       {
           try
           {
                Runjar.Runservices();
                Thread.sleep(SLEEP_TIME);//So that other thread also get the chance to execute.
           }
           catch (Exception ex)
           {
               ex.printStackTrace();
           }

       }    
   }
};
Thread thread2 = new Thread() {
   public void run() {
       while (linuxCmd)
       {
           try
           {
                ControllerApplication.linuxCmd();
                Thread.sleep(SLEEP_TIME);//So that other thread also get the chance to execute.
           }
           catch (Exception ex)
           {
               ex.printStackTrace();
           }
       }
   }
};
Thread thread3 = new Thread() {
   public void run() {
       while (insertLog)
       {
           try
           {
                Utils.insertLog();
                Thread.sleep(SLEEP_TIME);//So that other thread also get the chance to execute.
           }
           catch (Exception ex)
           {
               ex.printStackTrace();
           }
       }

   }
};
thread1.start();
thread2.start();
thread3.start();

如果要停止 runServices,请更改runServicesfalse. 同样对于linuxCmdinsertLog

于 2013-01-26T21:54:46.173 回答