Java Delay/Wait

后端 未结 4 946
悲&欢浪女
悲&欢浪女 2020-12-10 01:20

How do I delay a while loop to 1 second intervals without slowing down the entire code / computer it\'s running on to the one second delay (just the one little loop).

4条回答
  •  旧时难觅i
    2020-12-10 01:46

    My simple ways to delay a loop.

    I already put the codes here after failing to follow the stackoverflow's standards.

    //1st way: Thread.sleep : Less efficient compared to 2nd
    try {
      while (true) {//Or any Loops
       //Do Something
       Thread.sleep(sleeptime);//Sample: Thread.sleep(1000); 1 second sleep
      }
     } catch (InterruptedException ex) {
       //SomeFishCatching
     }
    //================================== Thread.sleep
    
    
    //2nd way: Object lock waiting = Most efficient due to Object level Sync.
    Object obj = new Object();
     try {
      synchronized (obj) {
       while (true) {//Or any Loops
       //Do Something
       obj.wait(sleeptime);//Sample obj.wait(1000); 1 second sleep
       }
      }
     } catch (InterruptedException ex) {
       //SomeFishCatching
     }
    //=============================== Object lock waiting
    
    //3rd way:  Loop waiting = less efficient but most accurate than the two.
    long expectedtime = System.currentTimeMillis();
    while (true) {//Or any Loops
       while(System.currentTimeMillis() < expectedtime){
         //Empty Loop   
       }
       expectedtime += sleeptime;//Sample expectedtime += 1000; 1 second sleep
       //Do Something
    }
    //===================================== Loop waiting
    

提交回复
热议问题