Java: Empty while loop

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

提交回复
热议问题