Results 1 to 12 of 12
  1. #1
    totalspelnerd is offline Member
    Join Date
    Mar 2012
    Location
    Sweden
    Posts
    88
    Rep Power
    0

    Default while loop not checking if it can loop

    I'm working on a project and realized something weird. My while loop isn't checking if it can loop.

    Here is a little example code:
    Java Code:
    public class WhileLoop {
    
    	boolean running = false;
    	int i;
    
    	public WhileLoop() {
    		running = true;
    		 runThread();
    		while (running) {
    			i++;
    		}
    		System.out.println("test");
    	}
    
    	public static void main(String args[]) {
    		new WhileLoop();
    	}
    
    	public void runThread() {
    		new Thread() {
    			public void run() {
    				while (true) {
    					try {
    						sleep(1000);
    					} catch (InterruptedException e) {
    						e.printStackTrace();
    					}
    					System.out.println(i);
    					running = false;
    				}
    			}
    		}.start();
    	}
    }
    Yes, I typed while(true), you mad?

    As you might see I started the thread inside runThread() and when one second has gone it prints the value of i (to see if it changes and it does) and sets running to false
    in my "main" while loop is checks if running = true and if it is keep looping. but when the thread changes running to false it doesn't get out of the loop. But if I make the loop print something (even System.out.println();) it checks if the statement is true and if it isn't it gets out if the loop.

    So my question: Why isn't the loop checking if the statement is true or not if I don't print something?

    Thanks for answers!
    Last edited by totalspelnerd; 06-18-2013 at 02:22 PM.

  2. #2
    AndrewM16921 is offline Senior Member
    Join Date
    Jan 2009
    Location
    NJ, USA
    Posts
    263
    Rep Power
    6

    Default Re: while loop not checking if it can loop

    Pretty sure it's a multi-threading issue. Add the "volatile" keyword to running, it seems to fix the issue. Then you still need to terminate the infinite-while-loop.
    Last edited by AndrewM16921; 06-18-2013 at 02:31 PM.

  3. #3
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    United States
    Posts
    3,318
    Rep Power
    5

    Default Re: while loop not checking if it can loop

    Whether I add the volatile keyword or not it works the same. And it appears to work correctly. The first loop which increments i, starts running. Your print statement gets a snapshot of i and prints it. But the other loop is still running. Then you set running to false and the other loops stops. Then every time you print i, it prints the same value because i is no longer incrementing.

    Regards,
    Jim
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  4. #4
    totalspelnerd is offline Member
    Join Date
    Mar 2012
    Location
    Sweden
    Posts
    88
    Rep Power
    0

    Default Re: while loop not checking if it can loop

    Then you still need to terminate the infinite-while-loop.
    yeah, this was just a test project. I know I shouldn't use while(true) this is just a SSCCI code.

  5. #5
    totalspelnerd is offline Member
    Join Date
    Mar 2012
    Location
    Sweden
    Posts
    88
    Rep Power
    0

    Default Re: while loop not checking if it can loop

    Quote Originally Posted by jim829 View Post
    Whether I add the volatile keyword or not it works the same. And it appears to work correctly. The first loop which increments i, starts running. Your print statement gets a snapshot of i and prints it. But the other loop is still running. Then you set running to false and the other loops stops. Then every time you print i, it prints the same value because i is no longer incrementing.

    Regards,
    Jim
    That is not what is happening to me. What operating system are you using? I'm using Windows 7, maybe that is the problem. Though the volatile made it work fine for me. I need to read up on what volatile is now, because I have no idea what it is.

  6. #6
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,304
    Blog Entries
    7
    Rep Power
    20

    Default Re: while loop not checking if it can loop

    Just for the fun of it: I used this example quite a lot:

    Java Code:
    public class T {
    	
        static volatile int x= 42;
    	
        public static void main(String[] args) {
    
        	new Thread(new Runnable() {
        		public void run() {
        			while (true) x= x++; // x stays 42
        		}
        	}).start();
        	
        	while (x == 42); // run forever
        	
        	System.out.println("huh?"); // this can't happen
        }
    }
    kind regards.

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  7. #7
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    United States
    Posts
    3,318
    Rep Power
    5

    Default Re: while loop not checking if it can loop

    On my machine, Windows XP, dual core processor, not only does it print out "huh?" everytime. but if I put in a print statement just after the while(x==42); loop, it prints out the value of x as either 42 or sometimes 43, followed by "huh?" I am running it via Eclipse Juno.

    Regards,
    Jim
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  8. #8
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,304
    Blog Entries
    7
    Rep Power
    20

    Default Re: while loop not checking if it can loop

    Quote Originally Posted by jim829 View Post
    On my machine, Windows XP, dual core processor, not only does it print out "huh?" everytime. but if I put in a print statement just after the while(x==42); loop, it prints out the value of x as either 42 or sometimes 43, followed by "huh?" I am running it via Eclipse Juno.
    Yup, why does it print out 43 sometimes or 42 but also the loop has stopped? But the one million dollar question is: do you need to replace the batteries or do you need to buy a new computer screen or does Eclipse need to be reinstalled or was it a disk fault? ;-)

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  9. #9
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    United States
    Posts
    3,318
    Rep Power
    5

    Default Re: while loop not checking if it can loop

    Not to hi-jack the OP's thread but here's your example, modified:

    Java Code:
    public class T {
         
        static volatile int x= 42;
         
        public static void main(String[] args) {
            new Thread(new Runnable() {
                public void run() {
                    while (true) x= x++; // x stays 42
                }
            }).start();
            System.out.println(x);
            while (x == 42); // run forever
            System.out.println(x);
            System.out.println("huh?"); // this can't happen
        }
    }
    Why *does* this print out the following sometimes?

    42
    42
    huh?

    Regards,
    Jim
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  10. #10
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,304
    Blog Entries
    7
    Rep Power
    20

    Default Re: while loop not checking if it can loop

    [QUOTE=jWhy *does* this print out the following sometimes?

    42
    42
    huh?
    [/QUOTE]

    The expression x++ changes the value of x, but x= x++ sets it back to its old value again, so for a fraction of a second the value of x is 43; if the other thread hits in, its loop will terminate and maybe prints 43 or 42; who knows?

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  11. #11
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    United States
    Posts
    3,318
    Rep Power
    5

    Default Re: while loop not checking if it can loop

    From this programmer's perspective, that's downright scary. :)

    Regards,
    Jim
    Last edited by jim829; 06-18-2013 at 04:41 PM.
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  12. #12
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,304
    Blog Entries
    7
    Rep Power
    20

    Default Re: while loop not checking if it can loop

    Quote Originally Posted by jim829 View Post
    From this programmer's perspective, that's downright scary. :)
    It's because of the fact that x= x++ isn't an atomic operation; nothing scary about it ;-)

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

Similar Threads

  1. Complicated for loop's and array checking
    By JordiLaForge in forum New To Java
    Replies: 1
    Last Post: 05-19-2013, 09:23 PM
  2. Replies: 2
    Last Post: 09-24-2012, 11:31 PM
  3. Replies: 2
    Last Post: 11-07-2011, 02:25 AM
  4. Replies: 1
    Last Post: 10-01-2011, 02:12 AM
  5. JTextField loop 2x for-loop WEIRD!
    By Streetproject in forum AWT / Swing
    Replies: 2
    Last Post: 02-16-2011, 05:46 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •