while working on a project I stumbled upon following thing:
I have an infinity loop that I want to break out of when a certain global static String is set to "START". I have a thread running that after 5 seconds sets the variable to "0" and after another 5 seconds to "START". So after ultimately 10 seconds the if-statement should be able to break out of the loop, but it does not.
If you however but a System.out.println(".") in the infinite loop after the if-statement, the loop registers the change and the program breaks out of the loop.
Firstly:
public static String response = null;
public static boolean ready = false;
This is the thread changing the String (class name: Text.java, implements Runnable):
@Override
public void run() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("setting to 0");
InfinityLoop.response = "0";
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("setting to start");
InfinityLoop.response = "START";
}
This is the program with the infinite loop that you cannot escape:
public static void main(String[] args) throws InterruptedException {
Text text = new Text();
new Thread(text).start();
while(true)
{
if((response != null) && (response.equals("START")))
break;
//System.out.println(response);
}
System.out.println("escaped");
}
}
This is the loop that you can escape:
public static void main(String[] args) throws InterruptedException {
Text text = new Text();
new Thread(text).start();
while(true)
{
if((response != null) && (response.equals("START")))
break;
System.out.println(response);
}
System.out.println("escaped");
}
}
My thought is that it might be the delay created by sysout but I cannot really believe that a delay that short could make such an impact..