java - 在 Java 中使用线程同时执行多个方法

标签 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中以简单有效的方式处理它。示例代码示例更佳。提前致谢。

最佳答案

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

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();

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

关于java - 在 Java 中使用线程同时执行多个方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14534216/

相关文章:

c - C 中的信号量和线程

java - 线程被多次调用

multithreading - 有人知道使用 .NET 4.0 任务进行并行编程模式/测试的良好资源吗?

java - Integer.toString() 在内部是如何工作的?

java - Tomcat 上的 AbstractMethodError setBinaryStream

java - 针对 javax 绑定(bind)注释而不是模式进行验证

java - JTextArea 会阻塞 Linux 上的线程吗?

c++ - InterlockedCompareExchange64 与 std::atomic compare_exchange

java - 对于 Grails 3 应用程序的独立 WAR 中的索引以外的操作,URL 映射被破坏

java - 如何从文件读入对象(构造函数)