在java中调用带超时的阻塞方法调用

时间:2012-07-06 13:08:43

标签: java java.util.concurrent concurrent-programming

我想在java中调用一个由于某种原因阻塞的方法。我想等待X分钟的方法,然后我想停止那个方法。

我在StackOverflow上阅读了一个解决方案,这让我第一次快速入门。我在这里写的是: -

ExecutorService executor = Executors.newCachedThreadPool();
    Callable<Object> task = new Callable<Object>() {
       public Object call() {
          return something.blockingMethod();
       }
    };
    Future<Object> future = executor.submit(task);
    try {
       Object result = future.get(5, TimeUnit.SECONDS); 
    } catch (TimeoutException ex) {
       // handle the timeout
    } catch (InterruptedException e) {
       // handle the interrupts
    } catch (ExecutionException e) {
       // handle other exceptions
    } finally {
       future.cancel(); // may or may not desire this
    }

但是现在我的问题是,我的函数可以抛出一些我必须捕获的异常并相应地执行一些任务。所以如果在代码中函数blockingMethod()有一些异常,我如何在Outer类中捕获它们?

4 个答案:

答案 0 :(得分:4)

您可以在所提供的代码中设置所有内容。只需替换

// handle other exceptions

进行异常处理。
如果您需要获取具体的Exception,请通过以下方式获取:

Throwable t = e.getCause();

要区分您的例外,您可以这样做:

if (t instanceof MyException1) {
  ...
} else if (t instanceof MyException2) {
  ...
...

答案 1 :(得分:1)

我想cause ExecutionException个实例中的{{1}}。

答案 2 :(得分:1)

ExecutionException catch块中的

:e.getCause() http://docs.oracle.com/javase/6/docs/api/java/lang/Throwable.html#getCause()

答案 3 :(得分:-1)

thread.sleep(x millisecods)将使线程停止x毫秒,然后它将恢复。另一种方法是调用thread.wait(x)(带有x的超时值),然后调用thread.notify()来“唤醒”睡眠线程。

相关问题