fxf*_*ure 54 java multithreading android handler timertask
每N毫秒调用一个函数最准确的方法是什么?
我使用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)
| 归档时间: |
|
| 查看次数: |
25426 次 |
| 最近记录: |