How to timeout a thread

后端 未结 17 1377
时光说笑
时光说笑 2020-11-22 01:01

I want to run a thread for some fixed amount of time. If it is not completed within that time, I want to either kill it, throw some exception, or handle it in some way. How

17条回答
  •  粉色の甜心
    2020-11-22 01:25

    I had the same problem. So i came up with a simple solution like this.

    public class TimeoutBlock {
    
     private final long timeoutMilliSeconds;
        private long timeoutInteval=100;
    
        public TimeoutBlock(long timeoutMilliSeconds){
            this.timeoutMilliSeconds=timeoutMilliSeconds;
        }
    
        public void addBlock(Runnable runnable) throws Throwable{
            long collectIntervals=0;
            Thread timeoutWorker=new Thread(runnable);
            timeoutWorker.start();
            do{ 
                if(collectIntervals>=this.timeoutMilliSeconds){
                    timeoutWorker.stop();
                    throw new Exception("<<<<<<<<<<****>>>>>>>>>>> Timeout Block Execution Time Exceeded In "+timeoutMilliSeconds+" Milli Seconds. Thread Block Terminated.");
                }
                collectIntervals+=timeoutInteval;           
                Thread.sleep(timeoutInteval);
    
            }while(timeoutWorker.isAlive());
            System.out.println("<<<<<<<<<<####>>>>>>>>>>> Timeout Block Executed Within "+collectIntervals+" Milli Seconds.");
        }
    
        /**
         * @return the timeoutInteval
         */
        public long getTimeoutInteval() {
            return timeoutInteval;
        }
    
        /**
         * @param timeoutInteval the timeoutInteval to set
         */
        public void setTimeoutInteval(long timeoutInteval) {
            this.timeoutInteval = timeoutInteval;
        }
    }
    

    Guarantees that if block didn't execute within the time limit. the process will terminate and throws an exception.

    example :

    try {
            TimeoutBlock timeoutBlock = new TimeoutBlock(10 * 60 * 1000);//set timeout in milliseconds
            Runnable block=new Runnable() {
    
                @Override
                public void run() {
                    //TO DO write block of code 
                }
            };
    
            timeoutBlock.addBlock(block);// execute the runnable block 
    
        } catch (Throwable e) {
            //catch the exception here . Which is block didn't execute within the time limit
        }
    

提交回复
热议问题