java 定时监测程序


package com.appstrategy.tests;

public abstract class SchedThread {
	protected static final long NEVER=Long.MAX_VALUE;
	
	//定义一个线程锁,保证当前只有一个工作在操作中
	private final Object lock = new Object();
	
	//定义一个Thread变量
	private Thread thread;
	
	//控制线程循环的开关
	private boolean active=true;
	
	//定义一个毫秒级的时间变量,指示何时执行下一个操作
	private long nextTime;
	
	/*
	 * 定义一个抽象方法用来获取下一个执行操作的时间,可以使用NEVER
	 */
	protected abstract long getNextTime();
	
	/*
	 * 定义一个抽象的方法,让子类来定义具体的工作过程
	 */
	protected abstract void executeWork();
	
	protected String getName(){
		return getClass().getName();
	}
	
	/*
	 * 启动线程
	 */
	public void start(){
		thread = new Thread(new Runnable(){
			@Override
			public void run() {
				runInternal();
			}
		},getName());
		thread.start();
	}

	/*
	 * 强迫停止线程,跳出for循环
	 */
	public void stop() throws InterruptedException{
		synchronized(lock){
			active = false;
			lock.notify();
		}
		thread.join();
	}
	
	/*
	 * 此方法可以在任何时候激活当前线程,让线程进入工作执行环节
	 */
	public void workAdded(long time){
		synchronized(lock){
			if(time<nextTime){
				//立即激活线程工作继续运行
				lock.notify();
			}
		}
	}
	
	/*
	 * 线程监测控制逻辑部分
	 */
	private void runInternal() {
		
		//无限循环
		for(;;){
			//该过程忽略了所有的Exception,保证线程不会因此而中断
			try{
				synchronized(lock){
					nextTime = getNextTime();
					
					//获得时间区间,即要等待的时间段
					long inteval = nextTime - System.currentTimeMillis();
					if(inteval > 0){
						try{
							lock.wait(inteval);
						}catch(InterruptedException e){
							//忽略此Exception
							
						}
					}
					
					//如果active为false,强制中断
					if(!active){
						break;
					}
				}
				//执行具体的工作
				executeWork();
			}catch(Throwable t){
				try{
					Thread.sleep(10000);
				}catch(InterruptedException ie){
					//忽略此Exception
					
				}
			}
		}
		
	}
	
}


举例:

package com.appstrategy.tests;

public class MyDataGenerator extends SchedThread{

	@Override
	protected long getNextTime() {
		// TODO Auto-generated method stub
		return System.currentTimeMillis()+2000L;
	}

	@Override
	protected void executeWork() {
		// TODO Auto-generated method stub
		//执行程序
		System.out.println("Executer ...");
		Monitor.execute();
	}

	public static void main(String argv[]) {   
		MyDataGenerator generator = new MyDataGenerator();
		generator.start();
		
	}
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值