package com.boz; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Date; import java.util.concurrent.*; import javax.swing.Timer; public class TimerTask { ExecutorService pool; private static TimerTask timeTask=null; public static void main(String[] args) throws InterruptedException { // TODO Auto-generated method stub TimerTask t=TimerTask.getTimerTask(10); for(int i=0;i<1000;i++){ t.AddTask(500, new task(i)); } Thread.currentThread().sleep(100000); } private TimerTask(int n) { // TODO Auto-generated constructor stub //初始化线程池 this.pool=Executors.newFixedThreadPool(n); } //如果没有初始化TimerTask类,则使用n作为线程池参数初始化线程; public static TimerTask getTimerTask(int n){ if(TimerTask.timeTask==null){ TimerTask.timeTask=new TimerTask(n); } return TimerTask.timeTask; } public Timer AddTask(int ms,Runnable obj){//添加定时任务,该定时任务 Timer t=new Timer(ms,new TimerTaskAction(obj)); System.out.printf("%s %s%n", new Date().toString(),"start Timer"); t.start(); return t; } class TimerTaskAction implements ActionListener{//定时任务的事件监听器只是简单的将任务对象添加到线程池中 private Runnable obj=null; public TimerTaskAction(Runnable Obj){ this.obj=Obj; } @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub pool.submit(this.obj); } } } class task implements Runnable{//该任务必须实现Runnable接口 private int n=0; public task(int iN){ this.n=iN; } @Override public void run() { // TODO Auto-generated method stub System.out.printf("%s %d%n", new Date().toString(),this.n); } }
<div class="iteye-blog-content-contain" style="font-size: 14px"></div>
鉴于java中定时器都会因为某个任务的执行缓慢而导致后面的任务不断延迟。所以编写了下面一个小程序做了一个延迟小的定时器。
说明:定时器使用javax.swing.Timer作为基础定时器,它在定时到达时会将任务添加到线程池FixedThreadPool中,任务由线程池运行。
疑问:javax.swing.Timer定时器从执行start到定时器触发有2到3秒的延迟。例如在第1秒执行start,定时为1000ms的情况下监听器会在第4第5秒执行;