Thread.sleep waits more than expected

后端 未结 4 1778
南笙
南笙 2021-01-17 20:14

The following code:

long msBefore = System.currentTimeMillis();
//Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
try
{Thread.sleep(200);
} catch (I         


        
相关标签:
4条回答
  • 2021-01-17 20:53

    I have a requirement to send n messages per second, I think wait/notify don't fit, correct?

    If you have a hard timing requirement, then you are going to need to use a real-time Java implementation. Mainstream SE and ME Java implementations are not suitable for hard realtime applications.

    There are various tricks you can use to meet such requirements "most of the time" ... but if your application / system gets overloaded you are liable start to missing the required message rate.

    Th real problem is not the accuracy of the timers, but the fact that a non-realtime scheduler won't (and can't) guarantee to schedule the thread to run as soon as the timer expires.

    0 讨论(0)
  • 2021-01-17 20:59

    There is no problem here. From javadoc:

    subject to the accuracy of system and schedulers.

    Usually, it is bad design to rely on the sleeping interval as it can be different on different systems and JVM implementations. Use wait() and notify() instead, or better - use java.util.concurrent package.

    0 讨论(0)
  • 2021-01-17 21:07

    You're not taking into account the time it spends processing.

        try {
            long processingStart = System.currentTimeMillis();
    
            long processingFinish = System.currentTimeMillis();
            long processTime = 600 - (processingFinish - processingStart);
            Thread.sleep(processTime);
    
        } catch (InterruptedException ex) {
    
        }
    
    0 讨论(0)
  • 2021-01-17 21:09

    If you really need fixed message rate, implement something like a spin-lock. It will consume single CPU core, but get you close.

    long nextTime = System.currentTimeMillis() + interval;
    while (keepRunning) {
       while (nextTime - System.currentTimeMillis() > 0)
           ;
       sendMessage();
       nextTime += interval;
    }
    
    0 讨论(0)
提交回复
热议问题