java中的任务调度:ScheduledExecutorService

通过ScheduledExecutorService中的方法,通过设定一个时间间隔,来执行定时任务,先看例子

测试用线程

public class ArcThread implements Runnable{

	private String threadName;
	private int delay;
	
	public ArcThread(String tn,int d){
		threadName = tn;
		delay = d;
	}
	
	@Override
	public void run() {
		System.out.println(threadName+"begin");
		if(delay>0){
			try {
				Thread.sleep(delay);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		System.out.println(threadName+"end");
		
	}

}


 

ScheduledExecutorService使用

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class TestScheduleThread {
	public static void main(String[] args) {
		ScheduledExecutorService executor = Executors.newScheduledThreadPool(5);

		ArcThread thread1 = new ArcThread("thread-1", 0);
		executor.schedule(thread1, 1, TimeUnit.SECONDS);

		ArcThread thread2 = new ArcThread("thread-2", 2500);
		executor.scheduleAtFixedRate(thread2, 0, 3, TimeUnit.SECONDS);

		ArcThread thread3 = new ArcThread("thread-3", 2500);
		executor.scheduleWithFixedDelay(thread3, 0, 3, TimeUnit.SECONDS);

	}
}

可以看到,常用的方法有schedule、scheduleAtFixedRate、scheduleWithFixedDelay,

schedule按顺序参数分别为执行的线程、开始延迟时间(例子中为1秒)、时间单位(例子中为秒)

scheduleAtFixedRate按顺序参数分别为执行的线程、开始延迟时间、间隔时间、时间单位

scheduleWithFixedDelay按顺序参数分别为执行的线程、开始延迟时间、间隔时间、时间单位

 

那么scheduleAtFixRate与scheduleWithFixeDelay有什么区别呢?

执行上面的例子,我们可以发现

thread2开始执行后,begin到end相差2秒,end到新的begin相差1秒

thread3开始执行后,begin到end相差2秒,end到新的begin相差3秒

由此得到的结论是:

scheduleAtFixedRate:第一次开始执行后计时,经过【间隔时间】后开始第二次执行

scheduleWithFixedDelay:第一次执行结束后计时,经过【间隔时间】后开始第二次执行

 

另外,对于scheduleAtFixedRate,如果【间隔时间】小于线程的执行时间,那么即时计时到了,还是会先等上一次执行完毕再开始下一次的

例子如下:

		ArcThread thread2 = new ArcThread("thread-2", 4000);
		executor.scheduleAtFixedRate(thread2, 0, 3, TimeUnit.SECONDS);


可以看到,end到新的begin几乎是没有间隔了,新的任务一直在等待旧的完成

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值