就我而言,我有三个不同类的三种方法。第一个是通过运行 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
tofalse
. Similarly forlinuxCmd
andinsertLog
关于java - 在 Java 中使用线程同时执行多个方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14534216/