Set running time limit on a method in java

后端 未结 4 780
一向
一向 2020-12-10 06:23

I have a method that returns a String, is it possible that after a certain time treshold is excedeed fot that method to return some specific string?

4条回答
  •  被撕碎了的回忆
    2020-12-10 07:04

    As answered of @MarcoS

    I found timeout is not raised if method is locking something and not release cpu time to Timer. Then Timer cannot start new thread. So I change a bit by start Thread immediately and sleep inside thread.

            InterruptTimerTaskAddDel interruptTimerTask = new InterruptTimerTaskAddDel(
                    Thread.currentThread(),timeout_msec);
    
            timer.schedule(interruptTimerTask, 0);
    
            /*
     * A TimerTask that interrupts the specified thread when run.
     */
    class InterruptTimerTaskAddDel extends TimerTask {
    
        private Thread theTread;
        private long timeout;
    
        public InterruptTimerTaskAddDel(Thread theTread,long i_timeout) {
            this.theTread = theTread;
            timeout=i_timeout;
        }
    
        @Override
        public void run() {
            try {
                Thread.currentThread().sleep(timeout);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace(System.err);
            }
            theTread.interrupt();
        }
    
    }
    

提交回复
热议问题