1、scheduleAtFixedRate 方法,顾名思义,它的方法名称的意思是:已固定的频率来执行某项计划(任务)。
2、scheduleWithFixedDealy,相对固定的延迟后,执行某项计划。
还是比较简单明了的描述比较好:第一个方法是固定的频率来执行某项计划,它不受计划执行时间的影响。到时间,它就执行。
执行结果:
2、scheduleWithFixedDealy,相对固定的延迟后,执行某项计划。
还是比较简单明了的描述比较好:第一个方法是固定的频率来执行某项计划,它不受计划执行时间的影响。到时间,它就执行。
而第二个方法,相对固定,据鄙人理解,是相对任务的。即无论某个任务执行多长时间,等执行完了,我再延迟指定的时间。也就是第二个方法,它受计划执行时间的影响。
package com;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class TestscheduleAtFixedRate {
public static void main(String[] args) {
// TODO 自动生成的方法存根
ScheduledExecutorService executor=Executors.newScheduledThreadPool(2);
long startTime=System.currentTimeMillis();
// executor.scheduleAtFixedRate(command, initialDelay, period, unit)
executor.scheduleWithFixedDelay(new MyRunableA_atfix(), 0, 2, TimeUnit.SECONDS);
System.out.println("A"+(System.currentTimeMillis()-startTime));
}
}
class MyRunableA_atfix implements Runnable{
@Override
public void run() {
// TODO 自动生成的方法存根
long startTime=System.currentTimeMillis();
System.out.println(startTime);
//System.out.println("begin A "+System.currentTimeMillis());
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
System.out.println(System.currentTimeMillis()-startTime);
// System.out.println("end A "+System.currentTimeMillis());
}
}
执行结果:
A1
1506748405777
2001
1506748409778
2001
1506748413780
2001