ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
long time;
@Override
public void run() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.e("scheduleAtFixedRate:"+ (System.currentTimeMillis()-time));
time = System.currentTimeMillis();
}
}, 5, 4, TimeUnit.SECONDS);
scheduledExecutorService.scheduleWithFixedDelay(new Runnable() {
long time;
@Override
public void run() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.e("scheduleWithFixedDelay:" +( System.currentTimeMillis()-time));
time = System.currentTimeMillis();
}
}, 5, 4, TimeUnit.SECONDS);
04-10 22:21:00.683 27044-27059/sjj.android.study E/Log:run(MainActivity.java:85): scheduleAtFixedRate:4002
04-10 22:21:04.681 27044-27059/sjj.android.study E/Log:run(MainActivity.java:85): scheduleAtFixedRate:3998
04-10 22:21:06.682 27044-27059/sjj.android.study E/Log:run(MainActivity.java:98): scheduleWithFixedDelay:8000
04-10 22:21:08.682 27044-27059/sjj.android.study E/Log:run(MainActivity.java:85): scheduleAtFixedRate:4000
04-10 22:21:12.682 27044-27059/sjj.android.study E/Log:run(MainActivity.java:85): scheduleAtFixedRate:4000
04-10 22:21:14.683 27044-27059/sjj.android.study E/Log:run(MainActivity.java:98): scheduleWithFixedDelay:8001
04-10 22:21:16.684 27044-27059/sjj.android.study E/Log:run(MainActivity.java:85): scheduleAtFixedRate:4002
04-10 22:21:20.682 27044-27059/sjj.android.study E/Log:run(MainActivity.java:85): scheduleAtFixedRate:3998
04-10 22:21:22.683 27044-27059/sjj.android.study E/Log:run(MainActivity.java:98): scheduleWithFixedDelay:8000
这里使用的newSingleThreadScheduledExecutor 两个任务时间产生了影响。