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

📄 timethread.java

📁 java定时器
💻 JAVA
字号:
/**
 *Copyright (c) 2007  All rights reserved.
 **/
package com.cbf.thread;

import org.apache.log4j.Logger;

import com.cbf.log.CbfLogger;

public class TimeThread extends Thread{
   private Task  curTask ;
   private long  firstTime;
   private long  periodTime;
   private boolean isCancal = false;
   private Object    sysObj = new Object();  

	
   public TimeThread(Task  curTask, long  firstTime, long  periodTime)
   {
	  this.curTask    = curTask;
	  this.firstTime  = firstTime;
	  this.periodTime = periodTime;
   }
   
   public void run()
   {   
	   logger.info("begin to start thread: " + curTask.getTaskName());
	   
	   long taskExecutionTime = System.currentTimeMillis();		 
	   long firstExecTime = firstTime;
	   long difference = 0;
	   while(!isCancal)
	   {
		   try{
			   if ( firstExecTime != -1)
			   {
				   taskExecutionTime = taskExecutionTime + firstTime;
				   if (firstExecTime >0)
				   {
					   synchronized(sysObj)
					   {
						  sysObj.wait(firstTime);
					   }
				   }
				   //execute the task;
				   TaskThread th = new TaskThread(curTask);
				   th.start();
				   
				   firstExecTime = -1;
				   difference = System.currentTimeMillis() - taskExecutionTime;				   
				   logger.info("time difference: " +  difference);
				
				   //
			   }
			   else
			   {
				   taskExecutionTime = taskExecutionTime + periodTime;
				   long waitTime = periodTime - difference;
				   if (waitTime > 0)
				   {
					   synchronized(sysObj)
					   {
						  sysObj.wait(waitTime);
					   }
				   }
				   //execute the task;
				   TaskThread th = new TaskThread(curTask);
				   th.start();
				   
				   difference = System.currentTimeMillis() - taskExecutionTime;				   
				   logger.info("time difference: " +  difference);
			   }
		   }catch(Exception ee){
			   logger.info("Thread Exception :"+ ee.getMessage());
		   }
	   }
	   
	   logger.info("Exit from cycle execution");
   }
   
   public void cancel()
   {
	   isCancal = true;
   }
}


/*
public abstract class Task {
	protected String taskName;
	
	public abstract void execute();


	public String getTaskName() {
		return taskName;
	}

	public void setTaskName(String taskName) {
		this.taskName = taskName;
	}
}
*/

⌨️ 快捷键说明

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