java 定时任务scheduleAtFixedRate 与 scheduleWithFixedDelay区别

1、scheduleAtFixedRate 方法,顾名思义,它的方法名称的意思是:已固定的频率来执行某项计划(任务)。 
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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值