在Java中,如果希望在不影响主线程运行的情况下处理异步方法的返回值,则可以使用以下方法之一:
- 使用
Executor
和Future
:可以使用Executor
框架中的ExecutorService
来创建一个线程池,然后使用submit
方法提交一个异步任务,该方法将返回一个Future
对象,可以使用get
方法获取异步任务的返回值。例如:
ExecutorService executor = Executors.newFixedThreadPool(10);
Future<Integer> result = executor.submit(new Callable<Integer>() {
public Integer call() throws Exception {
// 异步处理的代码
return 123;
}
});
// 在主线程中处理异步方法的返回值
int value = result.get();