您可以使用ExecutorServicea 异步运行任务,获取Future可以在完成任务时获取任务结果的任务.有一种get方法Future,你可以调用等待答案,超时.如果超时,您尝试通过调用取消任务cancel上Future.
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.
| 归档时间: |
|
| 查看次数: |
1651 次 |
| 最近记录: |