推荐还是用第二种方法,即用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的比较的更多相关文章

  1. 使用Timer和ScheduledThreadPoolExecutor执行定时任务

    Java使用Timer和ScheduledThreadPoolExecutor执行定时任务 定时任务是在指定时间执行程序,或周期性执行计划任务.Java中实现定时任务的方法有很多,主要JDK自带的一些 ...

  2. timer和ScheduledThreadPoolExecutor定时任务和每日固定时间执行

    //ScheduledThreadPoolExecutor每三秒执行一次 public static void main(String[] args) {        ScheduledThread ...

  3. Timer和ScheduledThreadPoolExecutor的区别

    Timer 基于单线程.系统时间实现的延时.定期任务执行类.具体可以看下面红色标注的代码. public class Timer { /** * The timer task queue. This ...

  4. 【高并发】ScheduledThreadPoolExecutor与Timer的区别和简单示例

    JDK 1.5开始提供ScheduledThreadPoolExecutor类,ScheduledThreadPoolExecutor类继承ThreadPoolExecutor类重用线程池实现了任务的 ...

  5. ScheduledThreadPoolExecutor Usage

    refs: https://blog.csdn.net/wenzhi20102321/article/details/78681379 对比一下Timer和ScheduledThreadPoolExe ...

  6. 深入理解Java线程池:ScheduledThreadPoolExecutor

    介绍 自JDK1.5开始,JDK提供了ScheduledThreadPoolExecutor类来支持周期性任务的调度.在这之前的实现需要依靠Timer和TimerTask或者其它第三方工具来完成.但T ...

  7. JUC源码分析-线程池篇(三)ScheduledThreadPoolExecutor

    JUC源码分析-线程池篇(三)ScheduledThreadPoolExecutor ScheduledThreadPoolExecutor 继承自 ThreadPoolExecutor.它主要用来在 ...

  8. 实例分析Scheduled Thread Pool Executor与Timer的区别

    摘要:JDK 1.5开始提供Scheduled Thread PoolExecutor类,Scheduled Thread Pool Executor类继承Thread Pool Executor类重 ...

  9. java多线程系类:JUC线程池:01之线程池架构

    概要 前面分别介绍了"Java多线程基础"."JUC原子类"和"JUC锁".本章介绍JUC的最后一部分的内容--线程池.内容包括:线程池架构 ...

随机推荐

  1. Java 性能优化

    http://eclipsesource.com/blogs/2013/01/21/10-tips-for-using-the-eclipse-memory-analyzer/ http://docs ...

  2. C# 中DataTable转成模型List

    C# 中DataTable转成模型List 引入using System.Reflection; 命名空间 使用注意实体类的属性名必须和DataTable的列名一致 使用: DBList<Sto ...

  3. XMLHttpRequest 对象

    XMLHttpRequest 对象 XML XSLTXML 解析器XMLHttpRequest 对象用于在后台与服务器交换数据. 什么是 XMLHttpRequest 对象? XMLHttpReque ...

  4. 由浅入深探究mysql索引结构原理、性能分析与优化 转

    第一部分:基础知识 第二部分:MYISAM和INNODB索引结构 1. 简单介绍B-tree B+ tree树 2. MyisAM索引结构 3. Annode索引结构 4. MyisAM索引与Inno ...

  5. 不透明度(兼容IE8,chrome,firefox)

    background-color: rgba(0, 0, 0, 0.2); background-color: black; opacity: 0.2; filter: Alpha(opacity=2 ...

  6. JaxWsDynamicClientFactory弃用了,改成org.codehaus.xfire.client;

    搞了好几天jar包冲突,最后修改接口调用方式 java.lang.IllegalStateException: Unable to create JAXBContext for generated p ...

  7. linux shell 整理收集(不断更新)

    1)主从复制延时判断 (转 http://www.cnblogs.com/gomysql/p/3862018.html) 说明: 不要通过Seconds_Behind_Master去判断,该值表示sl ...

  8. [linux] linux下编译安装zlib

    zlib官方网站:http://www.zlib.net上下载源码来安装zlib软件包. 目前最新版本zlib是zlib1.2.8,安装开始:$wget http://www.zlib.net/zli ...

  9. 关于JAVA中事件分发和监听机制实现的代码实例-绝对原创实用

    http://blog.csdn.net/5iasp/article/details/37054171 文章标题:关于JAVA中事件分发和监听机制实现的代码实例 文章地址: http://blog.c ...

  10. wcf stream 不知道长度的情况下,读取stream

    http://bbs.csdn.net/topics/360163784 string filepath = @"http://ww4.sinaimg.cn/thumbnail/6741e0 ...