⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 timer.java

📁 java多线程定时器
💻 JAVA
字号:
package practises.thread;

import java.util.Date;
import java.util.TreeSet;
import java.util.Comparator;

public class timer
{
  //已经排序的集合保存timer负责的任务
  //使用一个比较函数按时间执行任务  
  TreeSet tasks = new TreeSet(new TimerTaskComparator());
  
  //用来执行任务的线程
  TimerThread timer1;
  
  public timer() { this(false); }
  
  public timer(boolean isDaemon) 
  {
    timer1 = new TimerThread(isDaemon);  
    timer1.start();                      
  }
  
   //停止线程,放弃任务
   public void cancel()
   {
     synchronized(tasks) 
     {
       timer1.pleaseStop();
       tasks.clear();
       tasks.notify();
     }	
   }
   
    public void schedule(timertask task, long delay) 
    {
      task.schedule(System.currentTimeMillis() + delay, 0, false);
      schedule(task);
    }
    
    public void schedule(timertask task, Date time) 
    {
      task.schedule(time.getTime(), 0, false);
      schedule(task);
    }
    
    public void schedule(timertask task, Date firstTime, long period) 
    {
      task.schedule(firstTime.getTime(), period, false);
      schedule(task);
    }
  
    public void schedule(timertask task, long delay, long period) 
    {
      task.schedule(System.currentTimeMillis() + delay, period, false);
      schedule(task);
    } 
    
    public void scheduleAtFixedRate(timertask task, long delay, long period) 
    {
      task.schedule(System.currentTimeMillis() + delay, period, true);
      schedule(task);
    } 
    
    public void scheduleAtFixedRate(timertask task, Date firstTime,long period)
    {
      task.schedule(firstTime.getTime(), period, true);
      schedule(task);
    }
    
    void schedule(timertask task) 
    {
      synchronized(tasks) 
      {  
	tasks.add(task);   
	tasks.notify();    
      }
    }
    
    static class TimerTaskComparator implements Comparator 
    {
	public int compare(Object a, Object b) 
	{
	    timertask t1 = (timertask) a;
	    timertask t2 = (timertask) b;
	    long diff = t1.nextTime - t2.nextTime;
	    if (diff < 0) return -1;
	    else if (diff > 0) return 1;
	    else return 0;
	}
	public boolean equals(Object o) { return this == o; }
    }
    
   class TimerThread extends Thread
   {
     //此标志为真,表示线程停止。注意它被申明为volatile,这样可被另外一个
     //线程异步改变,所以线程必须总是读入真值,而且不用缓存版本。
     volatile boolean stopped = false;
     
     public TimerThread(boolean isDaemon) { setDaemon(isDaemon); }
     
     public void pleaseStop() { stopped = true; }
     
     public void run() 
     {
       timertask readyToRun = null;
       while(!stopped) 
       {
         if (readyToRun != null)
         {
           if (readyToRun.cancelled) 
           {  
	     readyToRun = null;
	     continue;	     
           }	
           readyToRun.run();
	   if (readyToRun.reschedule()) schedule(readyToRun);
	   readyToRun = null;
	   continue;
         }
         
         synchronized(tasks)
         {
       	   long timeout;
       	   if(tasks.isEmpty())
       	   {
       	     timeout=0;	
       	   }
       	   else
       	   {
       	     
       	     timertask t=(timertask) tasks.first();
       	     timeout=t.nextTime-System.currentTimeMillis();
       	     if(timeout<=0)
       	     {
       	       readyToRun=t;
       	       tasks.remove(t);
       	       continue;       	     	
       	     }	
       	   }
       	   
         try
       	   {
       	     tasks.wait(timeout);
       	   }
       	   catch(InterruptedException e){}
         }  
       }
     }     
   }
   
   public static class test
   {
     public static void main(String[] args)
     {
       final timertask t1=new timertask()
       {
         public void run()
         {System.out.println("boom");}
       };
       
       final timertask t2=new timertask()
       {
         public void run()
         {
           System.out.println("\tBOOM");	
         }	
       };
       
       final timertask t3=new timertask()
       {
         public void run()
         {
           t1.cancel(); 
           t2.cancel();	
         }	
       };
       
       final timer timer1=new timer();
       timer1.schedule(t1, 0, 500);     
       timer1.schedule(t2, 2000, 2000); 
       timer1.schedule(t3, 5000);       
       
       timer1.scheduleAtFixedRate(new timertask() 
       {
	 public int times = 5;
	 public void run() 
	 {
	   System.out.println(times--);
	   if (times == 0) timer1.cancel();
         }
       },5000,500);
     }	
   }
}


⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -