简体   繁体   English

Java中的无限循环和System.exit(0)

[英]Infinite Loop and System.exit(0) in java

我想知道如果进行无限循环(我正在检查程序是否已启动)是否会是错误的编码实践和/或某些后果,并且当条件Im检查变为真时,我将使用system.exit。

An active wait loop is usually a terrible idea. 主动等待循环通常是一个糟糕的主意。 It makes the entire machine slower (including start-up of the other program). 这会使整个机器变慢(包括其他程序的启动)。 Find a way to just listen for a program start event. 找到一种只监听程序启动事件的方法。 Without any details of your code, I can't provide any more specific suggestions. 没有您的代码的任何细节,我无法提供任何更具体的建议。

There's nothing inherently wrong with calling System.exit(0) ; 调用System.exit(0)并没有本质上的错误; it all depends on what kind of program it is. 这完全取决于它是哪种程序。 (Eg, a Swing application should just set DISPOSE_ON_CLOSE or EXIT_ON_CLOSE for the application's JFrame and then close the frame.) (例如,Swing应用程序应该只为该应用程序的JFrame设置DISPOSE_ON_CLOSEEXIT_ON_CLOSE ,然后关闭该框架。)

You may be better off using the java.util.Timer and java.util.TimerTask classes, and recursively relaunching the timer as it expires. 使用java.util.Timer和java.util.TimerTask类,并在计时器到期时递归地重新启动它可能会更好。 As the above post says there is nothing inherently wrong with using System.exit. 正如上面的帖子所述,使用System.exit并没有天生的错误。

public static void main(String[] args){
    Timer timer = new Timer(); //create a new timer
    timer.schedule(new TaskLoop(), 1000); //schedule the task for 1000ms (1 sec)
}
class TaskLoop extends TimerTask {
    public void run() {
        System.out.println("here"); //timer's up, do whatever you need to do
        Timer timer = new Timer();
        timer.schedule(new TaskLoop(), 1000); //start another timer.
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM