推荐还是用第二种方法,即用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. COM ,Threading Models,apartments,RPC

    Component Object Model (COM) https://msdn.microsoft.com/en-us/library/windows/desktop/ms680573%28v=v ...

  2. SQL Debugging

    C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\Binn>“C:\Program Files\Debugging ...

  3. LNMP-查看安装编译时参数

    查看mysql编译参数: cat /usr/local/mysql/bin/mysqlbug | grep CONFIGURE_LINE 查看apache编译参数: cat $apachehome$/ ...

  4. 爬虫入门---Python2和Python3的不同

    Python强大的功能使得在写爬虫的时候显得十分的简单,但是Python2和Python3在这方面有了很多区别. 本人刚入门爬虫,所以先写一点小的不同. 以爬取韩寒的一篇博客为例子: 在Python2 ...

  5. C语言的几种取整方法

    C语言的几种取整方法 来源:http://blog.sina.com.cn/s/blog_4c0cb1c001013ha9.html 1.直接赋值给整数变量.如: int i = 2.5; 或 i = ...

  6. js和css内联外联注意事项

    简单说:这两个问题其实是同一个问题,但是网上找了好久也找不到方法,外联的js和css文件里不能有任何HTML的标记注释,一旦有,浏览器就疯了!一去掉就好了!!! 问题:起因是网上看到一个css的表格样 ...

  7. Oracle中replace函数的使用

    例: select filefullname from sys_frmattachmentdb 查询的结果为: e:\GengBaoFile\TYGW\<历城区项目立项审批流程>.1079 ...

  8. 根据N种规格中的M种规格值生成的全部规格组合的一种算法

    近来在开发SKU模块的时候,遇到这样一个需求,某种商品有N(用未知数N来表示是因为规格的数组由用户制定且随时可以编辑的,所以对程序来说,它是一个未知数)类规格,每一类规格又有M个规格值,各种规格值的组 ...

  9. httpClenit的post出现乱码问题

    在使用httpClient.executeMethod(postMethod)的时候,发现一直存在乱码问题,”book is good“被转成”book+is+good“ 返回.查看源码后,发现pos ...

  10. 【java】 java 实现mysql备份

    使用java实现mysql的备份: public class MySQLBackUp { /** * Java代码实现MySQL数据库导出 * * @author GaoHuanjie * @para ...