ScheduledExecutorService学习

本文详细介绍了ScheduledExecutorService接口,它是Java并发工具包中用于计划任务执行的重要组件。文章解释了如何使用scheduleAtFixedRate和scheduleWithFixedDelay方法来安排定期执行的任务,并给出了具体的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

API的说明

public interface ScheduledExecutorService
   
    extends 
    ExecutorService
   
 

一个 ExecutorService,可安排在给定的延迟后运行或定期执行的命令。

schedule 方法使用各种延迟创建任务,并返回一个可用于取消或检查执行的任务对象。scheduleAtFixedRatescheduleWithFixedDelay 方法创建并执行某些在取消前一直定期运行的任务。

Executor.execute(java.lang.Runnable)ExecutorServicesubmit 方法所提交的命令,通过所请求的 0 延迟进行安排。schedule 方法中允许出现 0 和负数延迟(但不是周期),并将这些视为一种立即执行的请求。

所有的 schedule 方法都接受相对 延迟和周期作为参数,而不是绝对的时间或日期。将以 Date 所表示的绝对时间转换成要求的形式很容易。例如,要安排在某个以后的 Date 运行,可以使用:schedule(task, date.getTime() - System.currentTimeMillis(), TimeUnit.MILLISECONDS)。但是要注意,由于网络时间同步协议、时钟漂移或其他因素的存在,因此相对延迟的期满日期不必与启用任务的当前 Date 相符。 Executors 类为此包中所提供的 ScheduledExecutorService 实现提供了便捷的工厂方法。 

//设置了 ScheduledExecutorService ,在 1 小时内每 10 秒钟蜂鸣一次
class BeeperControl {
    private final ScheduledExecutorService scheduler = 
       Executors.newScheduledThreadPool(1);

    public void beepForAnHour() {
        final Runnable beeper = new Runnable() {
                public void run() { System.out.println("beep"); }
            };
        final ScheduledFuture<?> beeperHandle = 
            scheduler.scheduleAtFixedRate(beeper, 10, 10, SECONDS);
        scheduler.schedule(new Runnable() {
                public void run() { beeperHandle.cancel(true); }
            }, 60 * 60, SECONDS);
    }


1、scheduleAtFixedRate方法。

创建并执行一个在给定初始延迟后首次启用的定期操作,后续操作具有给定的周期;也就是将在 initialDelay 后开始执行,然后在 initialDelay+period 后执行,接着在 initialDelay + 2 * period 后执行,依此类推。如果任务的任何一个执行遇到异常,则后续执行都会被取消。否则,只能通过执行程序的取消或终止方法来终止该任务。如果此任务的任何一个执行要花费比其周期更长的时间,则将推迟后续执行,但不会同时执行。  

2、scheduleWithFixedDelay方法

创建并执行一个在给定初始延迟后首次启用的定期操作,随后,在每一次执行终止和下一次执行开始之间都存在给定的延迟。如果任务的任一执行遇到异常,就会取消后续执行。否则,只能通过执行程序的取消或终止方法来终止该任务。



实例:

	public static void main(String[] args) {
		ScheduledExecutorService executor = Executors
				.newScheduledThreadPool(50);
		for (int i = 0; i < 10; i++) {
			executor.scheduleAtFixedRate(new pop(), 0, 500,
					TimeUnit.MILLISECONDS);
		}
	}
class pop implements Runnable {
	public void run() {
			System.out.println(Thread.currentThread().getName());
	}
}
运行结果:
pool-1-thread-1
pool-1-thread-8
pool-1-thread-8
pool-1-thread-8
pool-1-thread-6
pool-1-thread-5
pool-1-thread-10
pool-1-thread-3
pool-1-thread-4
pool-1-thread-8
pool-1-thread-6
pool-1-thread-6
pool-1-thread-6
pool-1-thread-6
pool-1-thread-6


ps:使用多线程的时候要用循环创建实例进行执行。






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值