Java: Empty while loop

前端 未结 4 1417
醉酒成梦
醉酒成梦 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:03

    You probably need to declare path to be volatile. If the variable is not declared to be volatile then the compiler is free to cache its value in a register, and so any change to the value will not be recognized.

    But in general this style of code is very bad (except in some low-level real-mode stuff). While your while loop is looping it's consuming 100% of the CPU, so whatever other process there is to change the value of path may never get cycles to execute, and other processes that do mundane things like maintain communications links or update the mouse cursor location will not execute either.

    Best is to do some sort of event/message/semaphore based communications, so that your "loop" waits for a signal before continuing. "Acceptable" is to utilize some sort of delay, such as Thread.sleep, so that you only "poll" the variable every few milliseconds, say. You could also try Thread.yield, but that's sort of a crap-shoot and would not produce reliable results across a range of environments.

    0 讨论(0)
  • 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.)

    0 讨论(0)
  • 2021-01-17 15:30

    Rather than using a low level wait/notify approach, and to avoid busy waiting with a volatile, you can use a CountDownLatch. Because there is only one event to expect, instantiate the latch as:

    CountDownLatch latch = new CountDownLatch(1);
    

    Replace your while (path != null) with:

    latch.await();
    

    and in your main code, simply do:

    path = somePath;
    latch.countDown();
    
    0 讨论(0)
  • 2021-01-17 15:30

    the main thread does not exit the loop because because in while condition does not anything and checking condition is doing very speedy and while not sense changing variable. you have 2 way for resolve this problem: 1-in while loop waiting for a short time for example 5ms

        while(path != null){
         try{
           Thread.currentThread().sleep(50);
         }catch(){
           //do nothing
         }
        }
    

    2-define path variable as volatile:

      volatile String path;
    
    0 讨论(0)
提交回复
热议问题