2

私の場合、3 つの異なるクラスの 3 つのメソッドがあります。1 つ目は、jar ファイルを実行してサービスを継続的に実行することです。2 つ目は、ダウンしていないサービスがあるかどうかを確認し、サービスがダウンしていない場合は、jar ファイルを実行してサービスを実行し、3 つ目はログを挿入します。データベースだけでなくテキストファイルにも。

私はこれを行いましたが、正しく機能していません。

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 に答える