Timer与ScheduledThreadPoolExecutor的比较
推荐还是用第二种方法,即用ScheduledThreadPoolExecutor,因为它不需要像timer那样需要在里面再用一个线程池来保证计时的准确。(前提是线程池必须要大于1个线程)
1.timer中用线程池来执行任务,可以保证开始执行时间的准确,具体结束时间要以任务需要执行时间为准。如果未使用线程池,执行时间将被任务执行时间所影响。
package timer; import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import ch.qos.logback.core.joran.action.NewRuleAction; public class test {
private static final Logger log = LoggerFactory.getLogger(test.class); SimpleDateFormat sdformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); public static void main(String[] args) throws InterruptedException {
log.info("main start");
Timer timer = new Timer();
MyTask myTask = new MyTask("ONE");
MyTask myTask2 = new MyTask("TWO");
// 多长时间(毫秒)后执行任务
// timer.schedule(new MyTask(), 1000);
// 设定某个时间执行任务
// timer.schedule(new MyTask(), new Date(System.currentTimeMillis() +
// 1000 * 2));
// 第一次在指定firstTime时间点执行任务,之后每隔period时间调用任务一次。
// timer.schedule(new MyTask(), new Date(System.currentTimeMillis() +
// 1000 * 60*3),1000);
// delay时间后开始执行任务,并每隔period时间调用任务一次。
timer.scheduleAtFixedRate(myTask, 1000 * 3, 3000);
// timer.scheduleAtFixedRate(myTask2, 1000 * 3, 3000);
// 第一次在指定firstTime时间点执行任务,之后每隔period时间调用任务一次。
// timer.scheduleAtFixedRate(myTask, new Date(System.currentTimeMillis()
// + 1000 * 1), 2000); TimeUnit.SECONDS.sleep(10);
// timer.cancel();
// myTask.cancel();
// myTask2.cancel();
log.info("timer cancel");
}
} class MyTask extends TimerTask {
ExecutorService mExecutorService= Executors.newFixedThreadPool(3);
private static final Logger log = LoggerFactory.getLogger(test.class);
SimpleDateFormat sdformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); private String s; public MyTask(String s) {
this.s = s;
} @Override
public void run() { mExecutorService.execute(new Runnable() {
public void run() {
log.info(s + " 1 " + sdformat.format(new Date(System.currentTimeMillis())));
try {
TimeUnit.SECONDS.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
log.info(s + " 2 " + sdformat.format(new Date(System.currentTimeMillis())));
}
}); }
}
2.ScheduledThreadPoolExecutor类分scheduleWithFixedDelay和scheduleAtFixedRate方法,前者不包含执行时间,后者包含执行时间。
两种方法中如果都不再使用线程池,执行的开始时间也都会受执行时间影响。
package timer; import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimerTask;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; public class ScheduledThreadPoolExecutorTest {
private static final Logger log = LoggerFactory.getLogger(test.class);
SimpleDateFormat sdformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); public static void main(String[] args) throws InterruptedException {
MyTask2 task = new MyTask2("ONE");
MyTask2 task2 = new MyTask2("TWO");
ScheduledThreadPoolExecutor stpe = new ScheduledThreadPoolExecutor(5);
// stpe.scheduleWithFixedDelay(task, -2, 3, TimeUnit.SECONDS);
// stpe.scheduleWithFixedDelay(task2, -2, 3, TimeUnit.SECONDS);
ScheduledFuture<?> sf=stpe.scheduleAtFixedRate(task, -2, 3, TimeUnit.SECONDS);
TimeUnit.SECONDS.sleep(3);
// sf.cancel(false);
// stpe.shutdown();
}
} class MyTask2 extends TimerTask {
private static final Logger log = LoggerFactory.getLogger(test.class);
SimpleDateFormat sdformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); private String s; public MyTask2(String s) {
this.s = s;
} @Override
public void run() {
log.info(s + " 1 " + sdformat.format(new Date(System.currentTimeMillis())));
try {
TimeUnit.SECONDS.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
log.info(s + " 2 " + sdformat.format(new Date(System.currentTimeMillis())));
}
}
Timer与ScheduledThreadPoolExecutor的比较的更多相关文章
- 使用Timer和ScheduledThreadPoolExecutor执行定时任务
Java使用Timer和ScheduledThreadPoolExecutor执行定时任务 定时任务是在指定时间执行程序,或周期性执行计划任务.Java中实现定时任务的方法有很多,主要JDK自带的一些 ...
- timer和ScheduledThreadPoolExecutor定时任务和每日固定时间执行
//ScheduledThreadPoolExecutor每三秒执行一次 public static void main(String[] args) { ScheduledThread ...
- Timer和ScheduledThreadPoolExecutor的区别
Timer 基于单线程.系统时间实现的延时.定期任务执行类.具体可以看下面红色标注的代码. public class Timer { /** * The timer task queue. This ...
- 【高并发】ScheduledThreadPoolExecutor与Timer的区别和简单示例
JDK 1.5开始提供ScheduledThreadPoolExecutor类,ScheduledThreadPoolExecutor类继承ThreadPoolExecutor类重用线程池实现了任务的 ...
- ScheduledThreadPoolExecutor Usage
refs: https://blog.csdn.net/wenzhi20102321/article/details/78681379 对比一下Timer和ScheduledThreadPoolExe ...
- 深入理解Java线程池:ScheduledThreadPoolExecutor
介绍 自JDK1.5开始,JDK提供了ScheduledThreadPoolExecutor类来支持周期性任务的调度.在这之前的实现需要依靠Timer和TimerTask或者其它第三方工具来完成.但T ...
- JUC源码分析-线程池篇(三)ScheduledThreadPoolExecutor
JUC源码分析-线程池篇(三)ScheduledThreadPoolExecutor ScheduledThreadPoolExecutor 继承自 ThreadPoolExecutor.它主要用来在 ...
- 实例分析Scheduled Thread Pool Executor与Timer的区别
摘要:JDK 1.5开始提供Scheduled Thread PoolExecutor类,Scheduled Thread Pool Executor类继承Thread Pool Executor类重 ...
- java多线程系类:JUC线程池:01之线程池架构
概要 前面分别介绍了"Java多线程基础"."JUC原子类"和"JUC锁".本章介绍JUC的最后一部分的内容--线程池.内容包括:线程池架构 ...
随机推荐
- (转) SLAM系统的研究点介绍 与 Kinect视觉SLAM技术介绍
首页 视界智尚 算法技术 每日技术 来打我呀 注册 SLAM系统的研究点介绍 本文主要谈谈SLAM中的各个研究点,为研究生们(应该是博客的多数读者吧)作一个提纲挈领的摘要.然后,我 ...
- rac ASM下最简单归档开启方法
原创作品,出自 "深蓝的blog" 博客,深蓝的blog:http://blog.csdn.net/huangyanlong/article/details/47172639本次先 ...
- 写EXCEL(csv 可以用EXECEL打开,逗号分列隔符)
FILE *file = NULL; char path[]="D:\\Data\\Pos.csv"; CTime m_tDateTime; m_tDateTime = m_tDa ...
- sql server 如何在一个数据库中操作另一个数据库中的数据
INSERT INTO T1 SELECT * FROM OPENDATASOURCE( 'SQLOLEDB', 'Data Source=Serve ...
- ws318 配置
http://www.192ly.com/router-settings/huawei/ws318-sz.html
- 【转】C# 重写WndProc 拦截 发送 系统消息 + windows消息常量值(1)
C# 重写WndProc 拦截 发送 系统消息 + windows消息常量值(1) #region 截获消息 /// 截获消息 处理XP不能关机问题 protected ...
- 宝洁的Pvp
1.公司宗旨(Purpose) 我们生产和提供更佳品质及价值的产品,以改善全球消费者的生活.作为回报,我们将会获得领先的市场销售地位和利润增长,从而令我们的员工.我们的股东以及我们的生活.工作所处的社 ...
- oracle定时运行 存储过程
/* 查询: select job,broken,what,interval,t.* from user_jobs t; job job的唯一标识,自动生成的 broken 是否处于运行状态,N;运行 ...
- JDBC - Oracle PreparedStatement (GeneratedKey kind) ArrayIndexOutOfBoundsException
问题: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 12at oracle.jdbc. ...
- js 二维数组定义
1.二维数组声明方式是下面这样的: var images=new Array(); //先声明一维 for(var i=0;i<10;i++){ //一维长度为10 images[i]=new ...