While a no-body loop falls into an endless loop

I searched a lot but couldn't find a solution to this problem, so I asked a question here.

I made a small piece of code to reproduce the problem. therefore the following Java classes.

Class with main function:

package test;

public class Main {
    public static void main(String[] args) {
        Background ob = new Background();

        while(ob.val > 0);

        System.out.println("Program Completed");
    }
}

      

Runnable class:

package test;

public class Background implements Runnable {
    int val;
    Thread t;

    public Background() {
        val = 500;
        t=new Thread(this); 
        t.start();
    }

    @Override
    public void run() {
        while(val > -1000) {
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            val--;
        }
    }

}

      

Now this code doesn't print "Program Completed", so I think the while loop is in an infinite loop. But if I replace while(ob.val > 0);

with

while(ob.val > 0){
    System.out.println("val: "+ob.val);
};

      

or in any expression System.out.println()

, then I see "Completed Program". But yes, just any operator System.out.println()

. If I replace while(ob.val > 0);

with

int g;
while(ob.val > 0){
    g = 0;
};

      

Also, "Completed Program" is not displayed above the code.

The main code is too big to post here, so I replicated the problem. Tested replicated code on ubuntu 14.04, JDK -> jdk-8u31-linux-x64

I have not tested this replicated code on Windows. But I tested the main code on windows and it worked fine.

I am really confused about this type of behavior. Can anyone help me? Thanks in advance.

+3


source to share





All Articles