Java - alternative to thread.sleep

前端 未结 8 628
礼貌的吻别
礼貌的吻别 2020-11-30 10:00

I have a requirement to pause a while loop for a specific number of milliseconds. I have tried using Thread.sleep(duration) but it is not accurate, especially in a looping s

相关标签:
8条回答
  • 2020-11-30 10:18

    Try a ScheduledThreadPoolExecutor. It's supposed to give more reliable timing results.

    0 讨论(0)
  • 2020-11-30 10:22

    The delay is likely to arbitrarily chosen, so I would question your need to real time interval timing.

    If you need read time you need to busy wait for the time to reached. Giving up the CPU means you can't guarantee you will get it back exactly when you want.

    0 讨论(0)
  • 2020-11-30 10:23

    Java is not a real-time system, you can not make a thread go away and come back on such a tight schedule. To schedule your program execution down to millisecond you need to use a different platform - like simpleRTJ or Java Real-Time extension.

    0 讨论(0)
  • 2020-11-30 10:24

    You could implement wait/notify mechanism and delegate to another thread the responsibility of notify the other thread in wait state that the amount of time is passed and that it can go ahead ...

    For example when the threadA need to wait for a certain amount of time you can put the thread in wait state and start a timer task that after a certain amount of time (interval ) call notify and wake up the ThreadA that go ahead, this could be an alternative .

    0 讨论(0)
  • 2020-11-30 10:24

    The solution is to use a handler with a runnable and use of the method 'postDelayed'. Example:

    new Handler().postDelayed(new Runnable() {
    public void run () {
        // Do delayed stuff!
    }
    }, 5000L); //5 seconds delay 
    

    https://stackoverflow.com/a/21680858

    0 讨论(0)
  • 2020-11-30 10:27

    If you want to be accurate with sounds you use a sequencer and set the tempo in BPM: sequencer.setTempoInBPM(120);

    0 讨论(0)
提交回复
热议问题