java线程兑现超时

java线程实现超时

java线程实现超时
Javathread
用线程实现超时比较简单,大致思想为:定义一个超时守护线程,改线程启动时就sleep规定的超时时间;再执行一个命令或方法时启动该超时线程,如果该命令或方法在制定时间内执行完毕,则关闭守护线程,否则抛出timeout异常。具体代码如下:

定义一个超时守护线程TimeOutThread:
Java代码  收藏代码

    package com.pqrs.file.analyse.timeout; 
     
    public class TimeOutThread extends Thread { 
        /**
         * 超时时间
         */ 
        private long timeOut; 
        /**
         * 是否取消
         */ 
        private boolean cancel; 
        /**
         * 自定义超时异常
         */ 
        private TimeOutException timeOutException; 
         
        public TimeOutThread(long timeOut, TimeOutException timeOutException){ 
            super(); 
            this.timeOut = timeOut; 
            this.timeOutException = timeOutException; 
            //设置本线程为守护线程 
            this.setDaemon(true); 
        } 
         
        public synchronized void cancel() { 
            cancel = true; 
        } 
         
        public void run(){ 
            try{ 
                Thread.sleep(timeOut); 
                 
                if(!cancel){ 
                    throw timeOutException; 
                } 
            } catch(InterruptedException e){ 
                e.printStackTrace(); 
            } 
        } 
    } 



定义一个自己的超时异常:
Java代码  收藏代码

    package com.pqrs.file.analyse.timeout; 
     
    public class TimeOutException extends RuntimeException { 
        /**
          * 序列化号
          */ 
         private static final long serialVersionUID = -8078853655388692688L; 
     
         public TimeOutException(String errMessage) 
         { 
          super(errMessage); 
         } 
    } 



测试类:
Java代码  收藏代码

    public class TestTimeOut { 
    public static void main(String a[]){ 
            TimeOutThread timeOutThread = new TimeOutThread(3000, new TimeOutException("time out!")); 
            try{ 
                timeOutThread.start(); 
                Thread.sleep(5000); 
                timeOutThread.cancel(); 
            } catch(TimeOutException e){ 
                e.printStackTrace(); 
            } catch (InterruptedException e) { 
                e.printStackTrace(); 
            } 
        } 
    }