Spring @Async异步执行方法

测试代码:

 

Java代码   收藏代码
  1. <p>@RunWith(SpringJUnit4ClassRunner.class)</p>@ContextConfiguration(locations = { "/spring/*.xml" })  
  2. public class JobUtilsTest{  
  3.       
  4.     @Autowired  
  5.     private DaoService service;  
  6.   
  7.     @Test  
  8.     public void testAsync() throws Exception {  
  9.         System.out.println("start" );  
  10.         service.update(); // ★ 假设这个方法会比较耗时,需要异步执行  
  11.         System.out.println("end");  
  12.           
  13.           
  14.         Thread.sleep(3000); // 因为junit结束会结束jvm,所以让它等会异步线程  
  15.     }  
  16. }  

 

 DaoService代码:

Java代码   收藏代码
  1. @Service  
  2. public class DaoService {  
  3.     @Async  
  4.     public void update() {  
  5.         try {  
  6.             Thread.sleep(2000);  
  7.             // do something  
  8.         } catch (InterruptedException e) {  
  9.             e.printStackTrace();  
  10.         }  
  11.         System.out.println("operation complete.");  
  12.     }  
  13. }  

 

applicationContext.xml

 

 

Xml代码   收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"  
  4.     xmlns:context="http://www.springframework.org/schema/context"  
  5.     xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:task="http://www.springframework.org/schema/task"  
  6.     xsi:schemaLocation="http://www.springframework.org/schema/beans   
  7.     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
  8.     http://www.springframework.org/schema/context   
  9.     http://www.springframework.org/schema/context/spring-context-3.0.xsd  
  10.     http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">  
  11.   
  12.     <context:component-scan base-package="com.chinacache" />  
  13.    
  14.     <task:annotation-driven />  
  15.       
  16. </beans>  

 

输出结果:

 

start
end
operation complete.

 

可以看出,输出不是顺序执行,说明异步调用成功了。

猜你喜欢

转载自tjukk.iteye.com/blog/2187212