简体   繁体   中英

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. 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 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)

您的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

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;
}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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