As to the original question of why while (true);
takes up more CPU than while (true) { wait(1); }
, consider: a modern CPU can perform billions of instructions per second. With the wait(1)
loop, assuming it is perfect and waits exactly one millisecond each time, you're limiting the CPU to one thousand instructions per second. Without it, there's no limit and it can run the tight loop billions of times per second instead.
As to the new question of which is more efficient, the while (true) { wait(1); }
approach vs. wait()
and being notify()
ed...
Well let's say you're waiting on a condition. Option one:
while (true) {
wait(1);
if (condition()) {
break;
}
}
vs.
wait();
and elsewhere:
//code which causes condition() to be true
notify();
Say it takes 10 seconds for condition to be true. In the first approach, you call wait(1)
10,000 times and check condition()
10,000 times. In the second approach, you call wait()
once and notify()
once.