TimerTask与Thread.sleep vs Handler postDelayed – 每N毫秒最准确的调用函数?

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

  • 线程与Thread.sleep
  • 的TimerTask
  • 处理器postDelayed

我使用Thread.sleep修改了这个例子 ,它不是很准确。

我正在开发一个音乐应用程序,将在给定的BPM播放声音。 我知道创build一个完全准确的节拍器是不可能的,我不需要 – 只是寻找最好的方法来做到这一点。

谢谢

使用Timer有一些缺点

  • 它只创build一个线程来执行任务,如果一个任务需要很长时间才能运行,其他任务将受到影响。
  • 它不处理由任务抛出的exception,线程只是终止,这会影响其他计划任务,并且它们永远不会运行

ScheduledThreadPoolExecutor正确处理所有这些问题,它没有任何意义,使用计时器..有两种方法可以在你的情况下使用.. 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); 

在Android上,您可以使用自己的处理程序/消息队列创build线程。 这是相当准确的。 当您看到Handler 文档时,您可以看到它是为此devise的。

处理器有两个主要的用途: (1)安排消息和可运行子程序作为将来的某个点执行; 和(2)排队一个行动,要在你自己的另一个线程上执行。

他们都精确相同。 Java定时精度取决于系统定时器和调度器的精度和准确性,并不能保证。 请参阅Thread.sleep和Object.wait API。

使用TimerTask进行循环操作更好。 推荐