I have a function that needs to be called once a boolean variable is true. I tried using a while loop in a thread but it doesn’t work. Here is what I’ve tried:
public class MyRunnable implements Runnable {
public void run() {
while (true) {
if (conditions == true) {
System.out.println("second");
break;
}
}
}
public static void main(String args[]) {
boolean condition = false;
(new Thread(new MyRunnable())).start();
System.out.println("first\n");
// set conndition to true
condition = true;
}
}
The result shoud be:
first
second
Do not busy-wait for such conditions. Use a blocking idiom. For your simple case you would get away with a
new CountDownLatch(1). First, here’s your code, but fixed to compile and run the way you expect:For comparison, a program with a
CountDownLatch:To truly notice the difference, add a
Thread.sleep(20000)afterprintln("first")and hear the difference in the sound of your computer’s fan working hard to dissipate the energy the first program is wasting.