---
title: "异步方式调用同步方法"
author: "dikar"
date: "2012-03-16T21:11:53Z"
tags: []
categories: ["开源软件"]
slug: "untitled"
draft: false
lastmod: "2012-03-16T21:13:25Z"
id: 1455663
url: "https://dikar.iteye.com/blog/1455663"
---

系统中同步方法很多，当串行时响应时间会比较长，有些调用可以异步来做，当需要结果时只要有就行。如果调用的方法本身就是异步的这个还好。但是因为很多方法都是同步实现的，所以急需要一种框架或者工具来实现同步方法的异步调用，我搜索了下没找到比较好的解决方案，不过也有一些可供参考的，这里总结下：

 

 

1：NET Framework提供的异步调用同步方法

 

# 使用异步方式调用同步方法

[http://msdn.microsoft.com/zh-cn/library/2e08f6yc(v=vs.80).aspx](http://msdn.microsoft.com/zh-cn/library/2e08f6yc%28v=vs.80%29.aspx)

 

截取API使用方式如下：

 

 

```
// Create the delegate.
AsyncMethodCaller caller = new AsyncMethodCaller(ad.TestMethod);
       
// Initiate the asychronous call.
IAsyncResult result = caller.BeginInvoke(3000, 
                out threadId, null, null);

string returnValue = caller.EndInvoke(out threadId, result);
```

 

ad.TestMethod  就是需要异步调用的同步方法，可惜java没有这么简洁优美的语法。

 

2：目前找到的实现异步调用的java框架  asyn4j

[http://code.google.com/p/asyn4j/](http://code.google.com/p/asyn4j/)

 

国人原创的，api还可以，还不支持future模式，但是支持也很简单。

 

 

3：spring 3.0提供的任务调度

 

[http://static.springsource.org/spring/docs/3.0.5.RELEASE/reference/scheduling.html](http://static.springsource.org/spring/docs/3.0.5.RELEASE/reference/scheduling.html)

 

API使用例子：

 

```
simplest case, the annotation may be applied to a void-returning method.

@Async
void doSomething() {
    // this will be executed asynchronously
}
```

```
Unlike the methods annotated with the @Scheduled annotation, these methods can expect arguments, because they will be invoked in the "normal" way by callers at runtime rather than from a scheduled task being managed by the container. For example, the following is a legitimate application of the @Async annotation.

@Async
void doSomething(String s) {
    // this will be executed asynchronously
}
```

```
Even methods that return a value can be invoked asynchronously. However, such methods are required to have a Future typed return value. This still provides the benefit of asynchronous execution so that the caller can perform other tasks prior to calling get() on that Future.

@Async
Future<String> returnSomething(int i) {
    // this will be executed asynchronously
}
```