现在的位置: 首页 > 综合 > 正文

取代Java中的Thread.stop : 一个安全终止线程的通用模板

2013年11月10日 ⁄ 综合 ⁄ 共 1122字 ⁄ 字号 评论关闭

java线程中stop的弊端就不说了,学过多线程的应该都知道。

下面给出的一个安全终止线程的模板,虽然不算尽善尽美,但也应该能用。

如有任何疑问或建议,欢迎提出和讨论。

package concurrent;
/**
 * 继承本类的线程类需要可根据实际需要,覆盖taskBody(), cleanUp() 这两个方法
 * @author h
 *
 */
public class StoppableThread extends Thread {

	private boolean running = false;

	@Override
	final public void run() {
		running = true;
		try {
			while (!Thread.interrupted()) {
				taskBody();
			}
		} catch (InterruptedException e) {			
			System.out.println("handle exception, or exit");
		} finally {
			if (running == false) {
				cleanUp();
				return;
			}
		}
		// TODO Auto-generated method stub
	
	}

	protected void cleanUp() {
		System.out.println("do clean here");
		
	}

	protected void taskBody() throws InterruptedException{
		System.out.println("execute the main logic of task");		
	}
	//stop thread safely == terminate
	//注意:这个方法只能被调用方使用,而不能在本线程内部使用,因为方法中有join的调用,自身的调用会导致死锁
	public void terminate() {
		running = false;
		this.interrupt();
		
		try {
			//挂起调用方的线程,直到本线程执行完毕
			this.join();
		} catch (InterruptedException e) {
			//即使调用方强制使join中断,也没关系,因为本线程已经interrupt,它能够在结束之前做好清理工作
			System.out.println("do somthing to handle the execption, or just ignore it");
			
			e.printStackTrace();
		}
	}
	//test
	public static void main(String[] args) throws InterruptedException {
		StoppableThread st = new StoppableThread();
		st.start();
		Thread.sleep(2);		
		st.terminate();		
	}
}

抱歉!评论已关闭.