如何按时间中断方法执行?

fed*_*lov 1 java

假设方法A是调用方法B.方法可以A控制方法的执行时间B并将其中断,假设,60秒(方法B可以挂起)?

Jes*_*per 5

您可以使用ExecutorServicea 异步运行任务,获取Future可以在完成任务时获取任务结果的任务.有一种get方法Future,你可以调用等待答案,超时.如果超时,您尝试通过调用取消任务cancelFuture.

ExecutorService executorService = Executors.newSingleThreadExecutor();

// Callable that has a run() method that executes the task
Callable<String> callable = ...;

// Submit the task for execution
Future<String> future = executorService.submit(callable);

try {
    String result = future.get(30, TimeUnit.SECONDS);
    System.out.println("Result: " + result);
}
catch (TimeoutException e) {
    System.out.println("Timeout");
    future.cancel(true);
}
Run Code Online (Sandbox Code Playgroud)

并发API还有很多,请参阅包java.util.concurrent.