关于超时任务的实现


package test.thread;

import java.util.Timer;
import java.util.TimerTask;

public class MainThread {
	private Object lock = new Object();

	public void waitLock() throws InterruptedException {
		synchronized (lock) {
			lock.wait();
		}
	}

	public void notifyLock() {
		synchronized (lock) {
			lock.notify();
		}
	}

	/**
	 * @param args
	 *            关于超时任务的实现 实现功能:处理一批任务,如果某个任务的处理时间超过最大处理时间,则终止该任务的执行,继续执行下一个任务
	 *            实现思路:三线程实现,处理一个任务时,启动一个任务处理线程处理方案,再启动一个定时器线程检测是否超时,并通过一个同步变量保证任务时串行执行的。
	 * @throws InterruptedException
	 */
	public static void main(String[] args) {

		MainThread mainThread = new MainThread();

		for (int i = 2; i <= 20; i += 2) {
			System.out.println("start task!" + i);
			ProccessThread proccessThread = new ProccessThread(mainThread,i * 1000);
			MonitorThread monitorThread = new MonitorThread(mainThread);
			long maxProccessTime = 8 * 1000;// 每个任务的最大处理时间
			Timer timer = new Timer();
			timer.schedule(monitorThread, maxProccessTime);
			proccessThread.start();
			try {
				mainThread.waitLock();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			proccessThread.stop();
			timer.cancel();
			System.out.println("end task!" + i);
		}
	}

}

/**
 * 定时器线程检测
 * @author liuhui
 *
 */
class MonitorThread extends TimerTask {
	private MainThread mt;

	public MonitorThread(MainThread mt) {
		super();
		this.mt = mt;
	}

	@Override
	public void run() {
		System.out.println("ThreadID:" + " MonitorThread running!");
		mt.notifyLock();
	}

}

/**
 * 任务处理线程
 * @author liuhui
 *
 */
class ProccessThread implements Runnable {
	private MainThread mt;
	private Thread thread;
	private long processTime;
	public static int sec = 1;
	
	public ProccessThread(MainThread mt, long processTime) {
		super();
		this.mt = mt;
		this.processTime = processTime;
	}

	private void doSomething() {
		try {
			// do something
			// thread.sleep(100*1000); //异常情况
			// thread.sleep(1*1000); //正常情况
			thread.sleep(processTime); // 正常情况
			System.out.println("ThreadID:" + thread.getId() + ">>>  Normal Process! processTime=" + processTime);

		} catch (InterruptedException e) {
			// e.printStackTrace();
			System.out.println("ThreadID:" + thread.getId() + ">>>  AbNormal Proccess! processTime=" + processTime);
		}

	}

	public void run() {
		System.out.println("ThreadID:" + thread.getId() + ">>> starting!");
		doSomething();
		mt.notifyLock();
		System.out.println("ThreadID:" + thread.getId() + ">>> ending ok!");

	}

	public void start() {
		thread = new Thread(this);
		thread.start();

	}
	
	public void stop() {
		thread.interrupt();// 如果任务在正常时间内不能退出,认为产生interrupt,强行地退出 (run方法正常结束)
		thread.stop();
		try {
			Thread.sleep(sec * 1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		System.out.println("ThreadID:" + thread.getId() + ">>> stoping end!");
		thread = null;
	}
}


你可能感兴趣的:(thread)