TimerTask的VS视频下载器,处理器postDelayed - 最准确的调用函数每隔N毫秒? [英] TimerTask vs Thread.sleep vs Handler postDelayed - most accurate to call function every N milliseconds?

查看:236
本文介绍了TimerTask的VS视频下载器,处理器postDelayed - 最准确的调用函数每隔N毫秒?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What is the most accurate way to call a function every N milliseconds?

  • 螺纹带视频下载
  • 的TimerTask
  • 在处理程序postDelayed

我修改这个例子使用线程。睡觉,这不是很准确。

I modified this example using Thread.sleep and it's not very accurate.

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

I'm developing a music app that will play sounds at a given BPM. I understand it's impossible to create an entirely accurate metronome and I don't need to - just looking to find the best way to do this.

感谢

推荐答案

有使用定时器的一些缺点

There are some disadvantages of using Timer

  • 在它创建只有单个线程来执行任务,如果一个任务 需要很长时间才能运行,其他任务受到影响。
  • 在它不处理 抛出任务和线程刚刚结束,这会影响异常 其他计划的任务,他们从来没有运行
  • It creates only single thread to execute the tasks and if a task takes too long to run, other tasks suffer.
  • It does not handle exceptions thrown by tasks and thread just terminates, which affects other scheduled tasks and they are never run

的ScheduledThreadPoolExecutor交易正常使用所有这些问题,它没有任何意义,使用定时器。有可能是使用两种方法在你的情况.. scheduleAtFixedRate(...)和scheduleWithFixedDelay(..)

ScheduledThreadPoolExecutor deals properly with all these issues and it does not make sense to use Timer.. There are two methods which could be of use in your case.. scheduleAtFixedRate(...) and 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);

这篇关于TimerTask的VS视频下载器,处理器postDelayed - 最准确的调用函数每隔N毫秒?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆