Asgnc 分析

Spring中Async用法:在Java应用中,绝大多数情况下都是通过同步的方式来实现交互处理的;但是在处理与第三方系统交互的时候,容易造成响应迟缓的情况,之前大部分都是使用多线程来完成此类任务,就通过内置了@Async来完美解决这个问题。在Spring中,基于@Async标注的方法,称之为异步方法;这些方法将在执行的时候,将会在独立的线程中被执行,调用者无需等待它的完成,即可继续其他的操作。

 如何在Spring中启用@Async
   基于Java配置的启用方式:
@Configuration @EnableAsync public class SpringAsyncConfig { ... }
基于XML配置文件的启用方式,配置如下:
<task:executor id="myexecutor" pool-size="5" /> <task:annotation-driven executor="myexecutor"/>
以上就是两种定义的方式。
基于@Async无返回值调用
示例如下:
@Async //标注使用 public void asyncMethodWithVoidReturnType() { System.out.println("Execute method asynchronously. " + Thread.currentThread().getName()); }
使用的方式非常简单,一个标注即可解决所有的问题。
5. 基于@Async返回值的调用
示例如下:
@Async public Future<String> asyncMethodWithReturnType() { System.out.println("Execute method asynchronously - " + Thread.currentThread().getName()); try { Thread.sleep(5000); return new AsyncResult<String>("hello world !!!!"); } catch (InterruptedException e) { // } return null; }
摘自:http://www.jb51.net/article/105214.htm
posted @ 2018-03-26 10:31  尘埃未定  阅读(115)  评论(0编辑  收藏  举报