简体   繁体   English

从无限循环退出需要什么条件?

[英]What condition is needed to exit from infinite loop?

I have tried to write server side application. 我试图编写服务器端应用程序。 From school, I have leaned that I shouldnot let the code do infinite loop. 从学校开始,我就倾向于不要让代码进行无限循环。 But, in my server side application, I have not found the way that at what condition I should exit from the infinite loop. 但是,在我的服务器端应用程序中,我还没有找到在什么条件下应该退出无限循环的方式。 The code 编码

ServerSocket s = null;
s = new ServerSocket(5000 , 10);

Socket connection = null;
while(true)
{
    connection = s.accept();

    //create new thread to handle client
    new client_handler(connection).start();
}

You usually exit the loop when the JVM is shut down on a server. 通常,在服务器上关闭JVM时,您会退出循环。 Or when an exception is thrown and not caught. 或引发异常但未捕获异常时。 This is one case where the infinite loop is justified. 这是无限循环合理的一种情况。 If all went well, your server would be up forever. 如果一切顺利,您的服务器将永远运转。

Use a boolean flag that you can set to false at some point from inside or outside the loop. 使用boolean标志,您可以在循环的内部或外部将其设置为false

boolean started = true;
while (started) {
  ...
}

If the server should run and accept connections indefinitely, there is no need for exiting the loop. 如果服务器应无限期运行并接受连接,则无需退出循环。

If there is some command or condition, when the server should terminate, just do so 如果存在某些命令或条件,则应在服务器终止时执行此操作

while(true) {
    connection = s.accept();

    //create new thread to handle client
    new client_handler(connection).start();

    if (condition)
       break;
}

or even better 甚至更好

while (!condition) {
...
}

usually for these applications you use some flag to signal termination, like so: 通常对于这些应用程序,您使用一些标志来表示终止,例如:

private volatile boolean shouldDie = false; //thevolatile bit is important
...
while (!shouldDie) {
   //do some work
}

and then when you want the program to terminate you just need to set the flag to tru and wait (this is for graceful termination) 然后当您要终止程序时,只需将标志设置为tru并等待(这是正常终止的时间)

您的while语句总是要评估为true,因为您已传递值true而不使用任何条件

You could always do it like this: 您总是可以这样来做:

boolean loopCheck = true;
while(loopCheck)
{
//do stuff
loopCheck = false;
}

In PHP, not sure if it works in java, we can do 在PHP中,不确定它是否可以在Java中工作,我们可以

while(true)
{
//do stuff
break;
}
Use a boolean flag.

boolean flag=true;
while(flag)
{
// Your code here

if(condition)   //condition to exit loop
{
flag=false;
}
}

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

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