Java: Empty while loop

前端 未结 4 1416
醉酒成梦
醉酒成梦 2021-01-17 14:34

I\'m making a program with while loops that execute in this manner:

  1. Main thread enters a while loop.
  2. Nothing happens in the while loop.
  3. Threa
4条回答
  •  抹茶落季
    2021-01-17 15:16

    Busy waits are very expensive. I'd do it this way:

    Object LOCK = new Object(); // just something to lock on
    
    synchronized (LOCK) {
        while (path != null) {
            try { LOCK.wait(); }
            catch (InterruptedException e) {
                // treat interrupt as exit request
                break;
            }
        }
    }
    

    Then when you set path to null, just call

    synchronized (LOCK) {
        LOCK.notifyAll();
    }
    

    (You can just synchronize on this if both pieces of code are in the same object.)

提交回复
热议问题