시간 초과 작업의 실현에 관하여

3723 단어 thread


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;
	}
}



좋은 웹페이지 즐겨찾기