(原创)定时线程池中scheduleWithFixedDelay和scheduleAtFixedRate的区别
2015-12-01 15:48
656 查看
scheduleAtFixedRate 没有什么歧义,很容易理解,就是每隔多少时间,固定执行任务。
scheduleWithFixedDelay Parameters:
scheduleWithFixedDelay 比如当前一个任务结束的时刻,开始结算间隔时间,如0秒开始执行第一次任务,任务耗时5秒,任务间隔时间3秒,那么第二次任务执行的时间是在第8秒开始。
scheduleWithFixedDelay 比较容易有歧义
貌似也是推迟一段时间执行任务,但Oracle的解释如下,delay的意思是当结束前一个执行后延迟的时间
scheduleWithFixedDelay Parameters:
command- the task to execute
initialDelay- the time to delay first execution
delay- the delay between the termination of one execution and the commencement of the next
unit- the time unit of the initialDelay and delay parameters
scheduleWithFixedDelay 比如当前一个任务结束的时刻,开始结算间隔时间,如0秒开始执行第一次任务,任务耗时5秒,任务间隔时间3秒,那么第二次任务执行的时间是在第8秒开始。
import java.util.Date; public class WorkerThread implements Runnable{ private String command; public WorkerThread(String s){ this.command=s; } @Override public void run() { System.out.println(Thread.currentThread().getName()+" Start. Time = "+new Date()); processCommand(); System.out.println(Thread.currentThread().getName()+" End. Time = "+new Date()); } private void processCommand() { try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } } @Override public String toString(){ return this.command; } }
import java.util.Date; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; public class ScheduledThreadPool { public static void main(String[] args) throws InterruptedException { ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5); System.out.println("Current Time = "+new Date()); for(int i=0; i<10; i++){ Thread.sleep(1000); WorkerThread worker = new WorkerThread("do heavy processing"); //scheduledThreadPool.schedule(worker, 3, TimeUnit.SECONDS); //scheduledThreadPool.scheduleAtFixedRate(worker, 5, 5, TimeUnit.SECONDS); scheduledThreadPool.scheduleWithFixedDelay(worker, 5, 3, TimeUnit.SECONDS); } Thread.sleep(300000); scheduledThreadPool.shutdown(); while(!scheduledThreadPool.isTerminated()){ } System.out.println("Finished all threads"); } }
相关文章推荐
- cocos2dx3.4开发环境搭建详解(3) cocos2dx lua项目发布到android手机
- POJ-1042-Gone Fishing-枚举+贪心
- Linphone android 最新版编译(解决android5.0以上无法运行问题)
- android中Service和Thread的区别
- JS模拟百度音乐-全选操作
- javaSE(17)(打印流、转换流、对象流、配置文件和递归)
- iOS通知中心NSNotificationCenter
- ASP.NET如何禁止直接通过Url访问某个类型的文件(非权限),不定时补充
- Windows7+VS2010下OpenGL的环境配置
- 苹果的拒信
- 数据库分库分表(sharding)系列(五) 一种支持自由规划无须数据迁移和修改路由代码的Sharding扩容方案
- android适配不同分辨率的手机
- WPF 数据绑定 1_1 基础知识&绑定到元素属性
- Git 的 .gitignore 配置
- 左右视点视频质量差对3D视频总体质量的影响
- curl使用(待完善)
- js之全局与局部坑
- WPF 数据绑定 1_1 基础知识&绑定到元素属性
- adadmin: error while loading shared libraries: libclntsh.so.10.1
- Building For Different Environments with Maven