是否有任何好的示例可以开始使用 java 同步方法调用。我有两个方法 a 和 b 并且必须异步调用 b 。有什么建议吗?
问问题
87 次
2 回答
1
This is a big topic, with lots of gotchas. But you can get a good start by wrapping your method in a Callable<T>
and submitting that to ExecutorService.submit
. That will return back a Future<T>
, which has a method get()
. That last method returns T
, but not until the Callable<T>
finished.
For instance, let's say foo.b()
returns String
. You'd do something like:
Callable<String> asyncB = new Callable<String>() {
@Override
public String call() {
foo.b();
}
};
Future<String> futureB = myExecutorService.submit(asyncB);
// asyncB will now execute on a separate thread,
// which is managed by the ExecutorService
foo.a(); // synchronous call
String resultB = futureB.get();
If you're on Java 8, that first bit can just be:
Callable<String> asyncB = () -> foo.b();
于 2014-03-26T05:56:14.647 回答
0
如果您有任何机会使用 Spring,它们具有出色的异步支持。
http://docs.spring.io/spring/docs/3.0.x/reference/scheduling.html
于 2014-03-26T05:58:14.010 回答