【多线程】newScheduledThreadPool线程池比较scheduleAtFixedRate和scheduleWithFixedDelay

       上回说到,newScheduledThreadPool可以用来执行定时或者是周期性工作,但是newScheduledThreadPool里面有两个比较类似的schedule方法,分别是scheduleAtFixedRate和scheduleWithFixedDelay。那么整两个之间有什么不同呢?

例子one:

public static void main(String[] args) {
	ScheduledExecutorService scheduledThreadPool=Executors.newScheduledThreadPool(3);
	System.out.println(new Date().getSeconds());
	scheduledThreadPool.scheduleAtFixedRate(new Runnable(){
//	scheduledThreadPool.scheduleWithFixedDelay(new Runnable(){
		@Override
		public void run() {
			System.out.println(Thread.currentThread().getName()+"***"+new Date().getSeconds()+"===== I love LSR");
		}
	},1,3,TimeUnit.SECONDS);
}



从上面两张效果图来看,两个方法好像没有什么区别嘛。别着急,goto two!


例子two:

public static void main(String[] args) {
	ScheduledExecutorService scheduledThreadPool=Executors.newScheduledThreadPool(3);
	System.out.println(new Date().getSeconds());
	scheduledThreadPool.scheduleAtFixedRate(new Runnable(){
//	scheduledThreadPool.scheduleWithFixedDelay(new Runnable(){
		@Override
		public void run() {
			System.out.println(Thread.currentThread().getName()+"***"+new Date().getSeconds()+"===== I love LSR");
			try {
				Thread.sleep(3000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	},1,5,TimeUnit.SECONDS);
}


这两张效果对比较明显了,所以可以说明一点问题:

1、scheduleAtFixedRate,固定频率:每间隔固定时间就执行一次任务。注重频率。

2、scheduleWithFixedDelay,固定延迟:任务之间的时间间隔,也就是说当上一个任务执行完成后,我会在图定延迟时间后出发第二次任务。注重距上次完成任务后的时间间隔。


猜你喜欢

转载自blog.csdn.net/u013045878/article/details/76883571