使用Java中的线程同时执行多个方法 [英] Execute Multiple Methods Simaltaneously Using Thread In Java

查看:2529
本文介绍了使用Java中的线程同时执行多个方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

就我而言,我有三种不同类的三种方法.第一个是通过运行jar文件连续运行服务,第二个是检查是否有任何服务关闭,是否关闭,是否有任何服务关闭以及通过运行jar文件运行服务,第三个是插入日志在数据库以及文本文件中.

In my case I have three methods of three different class. First one is Run the Services continuously by running jar file, Second one is check if any services is down, if not down let it be and if any of the services is down run the service by running jar file and third one is insert the log in database as well as in text file.

我已经做到了,但是不能正常工作.

I have done this but its not functioning properly.

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中处理它.首选示例代码示例.提前致谢.

How can i handle it in java in simple and effective way. Sample code examples more preferred. Thanks In Advance.

推荐答案

如果要连续循环调用所有这些方法,则只需将代码更改为以下内容即可:

If you want to call all these methods continuously in a loop then just change your code to following :

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

If you want to stop runServices then change runServices to false. Similarly for linuxCmd and insertLog

这篇关于使用Java中的线程同时执行多个方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆