0

In this bit of code, there are 2 functionally identical while loops, but the first one prints "GO!" and the second one hangs forever. What is going on?

public class Tests {
    public static boolean go=false;
    public static void main(String[] args) {
        new TimerThread().start();

        // Loop 1 - Prints "GO!"
        while(true){
            System.out.print("");
            if(go){
                System.out.println("GO!");
                break;
            }
        }

        go=false;
        new TimerThread().start();

        // Loop 2 - Hangs
        while(true){
            if(go){
                System.out.println("GO!");
                break;
            }
        }
    }
    static class TimerThread extends Thread{
        public void run(){
            double timer = System.currentTimeMillis();
            while(timer>System.currentTimeMillis()-3000){
                go=false;
            }
            go=true;
        }
    }
}
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
redbart
  • 56
  • 1
  • 8
  • 1
    [What is the volatile keyword useful for](https://stackoverflow.com/q/106591) – Pshemo Dec 01 '19 at 21:16
  • 3
    So the immediate problem jumps out at me is `go` should be `volatile`. Although, I would suggest that either a `CountdownLatch` or `Semaphore` or even a simple monitor lock would be more efficient and less troublesome – MadProgrammer Dec 01 '19 at 21:16
  • In loop 2, if the main thread is higher priority (which I think it is) than the spawned threads AND go == false on entry to the loop - it will starve the spawned threads and go will never be true. –  Dec 01 '19 at 23:28

0 Answers0