保持Java程序永远运行或持续很长时间的最佳方法是什么? [英] What is the best way to keep a Java program running forever, or for a very long time?

查看:666
本文介绍了保持Java程序永远运行或持续很长时间的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有支持多个工作流程的java应用程序。使用从命令行传递给它的参数选择工作流。在其中一个工作流应用程序需要运行无限时间。我使用以下代码实现了相同的目标

I have java app which supports multiple workflows. Workflow is chosen using arguments passed to it from command line. In one of the workflow app needs to run for infinite time. I am achieving the same using following code

switch (args[0]) { 
    case "-runForever":
     // Some Computation
     Thread.sleep(Long.MAX_VALUE);
     break;
    case "otherCase:
     //dosomething
     break;
}

这是实现所需功能的好方法吗?

Is it a good way of achieving the required functionality?

推荐答案

你可以使用无限循环:

while(true){}

然而,这会毫无理由地耗尽CPU。相反,你可以调用wait()方法:

However, that would eat up the CPU for no reason. Instead, you could just call the wait() method:

synchronized{
   wait();
}

然后要恢复,你可以从另一个线程调用notify()。

Then to resume, you'd call notify() from another thread.

更多信息这里

您也可以启动另一个非守护程序线程。

You could also just start another non-daemon Thread.

这篇关于保持Java程序永远运行或持续很长时间的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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