如何等待2分钟才能完成方法,但是然后退出并继续?

时间:2014-01-16 07:08:08

标签: java threadpool delay

如何等待2分钟才能完成方法,但如果没有完成,请退出并继续?

我想等待2分钟才能完成方法,但是如果它在2分钟内没有完成,那么退出执行并继续前进。

4 个答案:

答案 0 :(得分:6)

使用jcabi API对这类事情非常有帮助:jcabi API

非常漂亮的基于注释的API,所以在你的情况下它会像这样工作:

@Timeable(limit = 120, unit = TimeUnit.SECONDS)
public void methodYouWantToTime(){...}

答案 1 :(得分:4)

以下组合可能有效:

时间跟踪:

// use this to record when a process started
long start = System.currentTimeMillis();
// subsequent calls can be used to track how long something has been running?
long timeInMillis = System.currentTimeMillis() - start;

单独的过程:

java.lang.Thread // Extend this class
// And implement your own run() method.

在等待单独线程完成的循环中,您可以使用:

Thread.interrupt(); // This method could then be used to stop the execution
Thread.stop(); // This is also another way to stop execution, but it is deprecated and its use is frowned upon!

HTH

答案 2 :(得分:3)

在Executor和Futures的帮助下,我认为这可能会有所帮助

    ExecutorService executor = Executors.newCachedThreadPool();

    Future<String> future = executor.submit( new Callable<String>() {
        public String call() throws Exception {
            return someVeryLengthMethod();
        }});

    String result = null;
    try {
        result = future.get(2, TimeUnit.MINUTES);
    } catch (InterruptedException e) {
        // Somebody interrupted us
    } catch (ExecutionException e) {
        // Something went wring, handle it...
    } catch (TimeoutException e) {
        // Too long time
        future.cancel(true);
    }
    // Continue with what we have...

这将等待指定时间的答案,如果结果在该时间内不可用,则取消将来(可能会或可能不会实际停止执行该任务),并且代码可以继续。

答案 3 :(得分:0)

这个问题在不同的主题中解释。最好的方法是使用具有超时的ThreadPool(参见ExecutorService)。

示例,提交任务并等待60秒以获得答案:

ExecutorService pool = Executors.newCachedThreadPool();
    Future<Object> future = pool.submit(new Callable<Object>() {
        @Override
        public Object call() throws Exception {
            Thread.sleep(1000);
            return this;
        }
    });
    Object result = future.get(60, TimeUnit.SECONDS);

如果您想等待任务完成但不期望任何输出,请更好地使用:

pool.submit(new Runnable() {
        @Override
        public void run() {
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    });
    // Wait until the task is completed, then shut down the pool
    pool.awaitTermination(60, TimeUnit.SECONDS);

此主题中的更多详细信息:ExecutorService that interrupts tasks after a timeout