1

When executing a while loop, does java constantly check if the parameter(s) are true? For example if a while loop is

while(k=7) {
    Thread.sleep(5000);
}

but during the 5 seconds another thread changes k to 8, would the loop continue waiting or exit immediately?

arshajii
  • 127,459
  • 24
  • 238
  • 287
user760220
  • 1,207
  • 2
  • 13
  • 12
  • 4
    you are using `=` instead of `==`. A typo may be. Second, is `k` an instance variable? – Rohit Jain Jul 31 '13 at 16:41
  • What is `k`? You've left out the code related to it… – e-sushi Jul 31 '13 at 16:45
  • Each line on does what it says and no more. It doesn't know what other lines around it might do in another scenario. When it is it sleep()ing, that is all it is doing. BTW if it did stop immediately, what would be the point of setting a sleeping time? – Peter Lawrey Jul 31 '13 at 16:46

3 Answers3

7

No, it will only check when the execution path takes it there. Thus, it will check every 5 seconds in your example.

If you wanted to be notified immediately, you would have to use wait(), notify(), or some other synchronization method.

Here is an example

Community
  • 1
  • 1
Trenin
  • 2,041
  • 1
  • 14
  • 20
5

No. Even if k were volatile (or, worse, changed from another thread without you making it volatile; bad idea) or an object whose properties could change via the methods called inside the loop, it will only be checked at the end of the loop body, deciding to repeat the body or continue past the loop.

You can break out of the loop by interrupting the thread and having the catch outside the loop, or with an internal check and break.

nanofarad
  • 40,330
  • 4
  • 86
  • 117
2

The condition is checked once at the start and, if the loop is entered, once after the execution of the body on each iteration. So no, it will not exit immediately, even if k is altered while the body is being executed.

Oh, and you probably meant k == 7 (recall that == compares while = assigns). Some will even write 7 == k to avoid potentially making this mistake.

This doesn't really have much to do with threads. For instance, consider:

int k = 7;
while (k == 7) {
    k = 8;
    System.out.println("here!");
}
here!

Notice how the body is still fully executed even though k is immediately changed to a value that no longer satisfies the loop condition.

arshajii
  • 127,459
  • 24
  • 238
  • 287