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

fxf*_*ure 54 java multithreading android handler timertask

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

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

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

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

谢谢

小智 60

使用Timer有一些缺点

  • 它只创建单个线程来执行任务,如果任务运行时间太长,其他任务就会受到影响.
  • 它不处理由任务抛出的异常,并且线程只是终止,这会影响其他计划任务,并且它们永远不会运行

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);
Run Code Online (Sandbox Code Playgroud)


mle*_*zey 7

在Android上,您可以使用自己的Handler/Message Queue创建Thread.这很准确.当您看到Handler 文档时,您可以看到它是为此而设计的.

Handler有两个主要用途:(1)安排消息和runnables作为未来某些点执行; (2)将要在不同于自己的线程上执行的操作排入队列.