线程执行超时

守护线程定义:

package loci.currency.thread.daemon;

public class TimeoutThread extends Thread{

    private int timeout;
    
    private boolean isCancel = false;
    
    public TimeoutThread(int timeout,final Thread currentThread) {
        super();
        this.timeout = timeout;
        
        this.setDaemon(true);
        
        this.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
            
            @Override
            public void uncaughtException(Thread t, Throwable e) {
                currentThread.interrupt();
            }
        });
        
    }
    
    @Override
    public void run() {
        try {
            Thread.sleep(timeout);
            if(!isCancel){
                throw new IllegalStateException("线程超时了!");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    
    public void cancel(){
        isCancel = true;
    }
}

demo:

package loci.currency.thread.daemon;


/**
 * @author yaohw
 *
 */
public class TestDaemonMain {
    
    public static void main(String[] args) {
        TimeoutThread t = new TimeoutThread(1000,Thread.currentThread());
        try {
            t.start();
            Thread.sleep(100000);
            t.cancel();
        } catch (Exception e) {
            e.printStackTrace();
        }
        
    }
}
posted @ 2012-11-23 00:57  echx  阅读(262)  评论(0编辑  收藏  举报