在Java中以线程方式执行多个方法

时间:2013-01-26 05:37:55

标签: java multithreading

在我的情况下,我有三种不同类的方法。第一个是通过运行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中处理它。示例代码示例更优选。提前致谢。

1 个答案:

答案 0 :(得分: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,请将runServices更改为false。   同样适用于linuxCmdinsertLog