user760220
user760220

Reputation: 1237

Will while-loop stop mid-execution?

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?

Upvotes: 1

Views: 3324

Answers (3)

arshajii
arshajii

Reputation: 129517

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.

Upvotes: 2

nanofarad
nanofarad

Reputation: 41281

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.

Upvotes: 5

Trenin
Trenin

Reputation: 2063

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

Upvotes: 7

Related Questions