如何设置在 java 中执行某些方法的时间?

How to set up time for a execute some method in java?

我有一些方法叫做 exampleMethod。 当我有时调用这个方法(它与网络一起工作......)时,网络慢时需要很长时间......

如何设置执行的最大时间?

例如10s。

像这样...

try {
      exampleMethod();
} catch(Exeption e) {
      LoggError("I was to slow");
}

我希望,你能理解我,谢谢你的帮助。,

您可以使用 ExecutorService,设置超时值并在超过超时后取消未来以请求线程中断:

    ExecutorService executorService = Executors.newSingleThreadExecutor();
    Future<?> future = null;
    try {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                while (true) {
                    // it the timeout happens, the thread should be interrupted. Check it to let the thread terminates.
                    if (Thread.currentThread().isInterrupted()) {
                        return;
                    }
                    exampleMethod();
                }

            }
        };

        future = executorService.submit(r);
        future.get(10, TimeUnit.SECONDS);
    }

    // time is passed
    catch (final TimeoutException e) {
        System.out.println("I was to slow");
        // you cancel the future
        future.cancel(true);
    }
    // other exceptions
    catch (Exception e) {
        e.printStackTrace();
    } finally {
        executorService.shutdown();
    }
}