当前位置:编程学习 > JAVA >>

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

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

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

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

 


view plaincopy to clipboardprint?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();      
    } 

 作者“sjtu_huang的专栏”

补充:综合编程 , 安全编程 ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,