ScheduledExecutorService

ScheduledExecutorService是Java中用于定时执行任务的接口,基于多线程并使用延迟队列。可以使用newScheduledThreadPool创建多线程线程池,或newSingleThreadScheduledExecutor创建单线程线程池。scheduleWithFixedDelay方法实现任务的固定延迟执行,而delayedExecute和ensurePrestart方法则涉及线程池的内部工作。需要注意的是,异常会导致所有任务终止,任务执行时间超过间隔时不会并发执行,需处理异常。
摘要由CSDN通过智能技术生成

public interface ScheduledExecutorService extends ExecutorService 

基于多线程,任务间不会互相影响

内部使用延迟队列,本身基于等待/唤醒机制

创建:

1、public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize)创建线程池,参数即池中保存的线程数,返回新创建的线程池

2、public static ScheduledExecutorService newSingleThreadScheduledExecutor()单线程,顺序执行任务,新增任务在队列中排队等待,看到名字应该也可以guess这个是和单线程池结合

方法

/**
 * 创建并执行在给定延迟后启用的一次性操作
 *
 * @param command 要执行的任务 
 * @param delay 从现在开始延迟执行的时间 
 * @param unit 延时参数的时间单位 
 * @return 表示任务等待完成,并且其的ScheduledFuture get()方法将返回 null完成后 , 调度之后可通过Future.get()阻塞直至任务执行完毕
 * @throws RejectedExecutionException 如果任务无法安排执行 
 * @throws NullPointerException 如果命令为空 
 */
1. public ScheduledFuture<?> schedule(Runnable command,
                                      long delay, TimeUnit unit);

/**
 * 创建并执行在给定延迟后启用的ScheduledFuture,只执行一次
 *
 * @param callable 执行的功能 
 * @param delay 从现在开始延迟执行的时间 
 * @param unit 延迟参数的时间单位 
 * @param <V> the 可调用结果的类型 
 * @return一个可用于提取结果或取消的ScheduledFuture:调度之后可通过Future.get()阻塞直至任务执行完毕,并且可以获取执行结果
 * @throws RejectedExecutionException 如果该任务无法安排执行 
 * @throws NullPointerException 如果callable为空 
 */
2. public <V> ScheduledFuture<
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值