每N毫秒调用一个函数的最准确方法是什么?

带有Thread.sleep的

  • 线程
  • TimerTask
  • 带有postDelayed 的
  • 处理程序

    我使用Thread.sleep修改了this example,它不是很准确。

    我正在开发一个音乐应用程序,它将以给定的BPM播放声音。我知道创建一个完全准确的节拍器是不可能的,而且我不需要-只是寻找找到最佳的节拍器方法。

    谢谢

    最佳答案

    使用计时器有一些缺点

  • 它仅创建一个线程来执行任务,如果有任务
    运行时间太长,其他任务也受累。
  • 它不处理
    任务和线程抛出的异常只会终止,从而影响
    其他计划的任务,它们永远不会运行

  • ScheduledThreadPoolExecutor可以正确处理所有这些问题,因此使用Timer没有意义。.在您的情况下,可以使用两种方法。.scheduleAtFixedRate(...)和scheduleWithFixedDelay(..)
    class MyTask implements Runnable {
    
      @Override
      public void run() {
        System.out.println("Hello world");
      }
    }
    
    ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor(1);
    long period = 100; // the period between successive executions
    exec.scheduleAtFixedRate(new MyTask(), 0, period, TimeUnit.MICROSECONDS);
    long delay = 100; //the delay between the termination of one execution and the commencement of the next
    exec.scheduleWithFixedDelay(new MyTask(), 0, delay, TimeUnit.MICROSECONDS);
    

    10-06 07:15
    查看更多