在java中设置方法的运行时间限制

Lon*_*don 8 java

我有一个返回String的方法,是否有可能在某个时间阈值之后,该方法返回一些特定的字符串?

ska*_*man 14

番石榴库有一个非常好的TimeLimiter,可以让你做到这一点,就会向由接口定义的任何方法.它可以为您的对象生成具有"内置"超时的代理.


Mar*_*coS 11

我在过去使用外部进程生成类似的东西Runtime.getRuntime().exec(command).我想你可以在你的方法中做这样的事情:

Timer timer = new Timer(true);
InterruptTimerTask interruptTimerTask = 
    new InterruptTimerTask(Thread.currentThread());
timer.schedule(interruptTimerTask, waitTimeout);
try {
    // put here the portion of code that may take more than "waitTimeout"
} catch (InterruptedException e) {
    log.error("timeout exeeded);
} finally {
    timer.cancel();
}
Run Code Online (Sandbox Code Playgroud)

这是 InterruptTimerTask

/*
 * A TimerTask that interrupts the specified thread when run.
 */
protected class InterruptTimerTask extends TimerTask {

    private Thread theTread;

    public InterruptTimerTask(Thread theTread) {
        this.theTread = theTread;
    }

    @Override
    public void run() {
        theTread.interrupt();
    }

}
Run Code Online (Sandbox Code Playgroud)

  • 我在try/catch中遇到错误:"InterruptedException的无法访问的catch块".永远不会从try语句体中抛出此异常 (3认同)