如何在Java中实现同步方法超时?

2022-09-01 18:36:44

我有一个同步执行路径,需要在给定的时间范围内完成或超时。假设我有一个带有main()方法的类,其中我调用方法A(),该方法又调用B(),然后依次调用相同或不同类的C().....所有这些都是同步的,而无需使用外部资源,如数据库,Web服务或文件系统(其中每个资源都可以使用TxManager或相应的超时API独立超时)。因此,它更像是CPU或内存密集型计算。如何在Java中为它的超时编写代码?

我已经看过TimerTask,但更多的是使流程异步和调度任务。还有其他建议吗?


答案 1

你应该使用ExecutorService来做到这一点。

ExecutorService executor = Executors.newSingleThreadExecutor();
Future<String> future = executor.submit(new Callable() {

    public String call() throws Exception {
        //do operations you want
        return "OK";
    }
});
try {
    System.out.println(future.get(2, TimeUnit.SECONDS)); //timeout is in 2 seconds
} catch (TimeoutException e) {
    System.err.println("Timeout");
}
executor.shutdownNow();

答案 2

您可以运行并行线程,该线程将等待指定的超时并中断当前线程,然后运行 。但是a、b和c必须是可中断的,即定期检查当前线程中断标志并抛出DistrucatedException,否则它将无法工作A()

    final Thread current = Thread.currentThread();
    Thread timer = new Thread() {
        public void run() {
            try {
                Thread.sleep(5000);
                current.interrupt();
            } catch (InterruptedException e) {
                // timer stopped
            }
        };
    };
    try {
        A();  // this throws InterruptedException if interrupted by timer
        timer.interrupt(); // no timeout lets stop the timer
    } catch (InterruptedException e) {
        // timeout
    }

推荐