/**
* @author fengzp
* @date 17/5/8
* @email fengzp@gzyitop.com
* @company 广州易站通计算机科技有限公司
*/
@SpringBootApplication
@EnableAsync
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
测试类
/**
* @author fengzp
* @date 17/5/8
* @email fengzp@gzyitop.com
* @company 广州易站通计算机科技有限公司
*/
@Component
public class AsyncTest {
public static Random random =new Random();
/**
* @Async所修饰的函数不要定义为static类型,否则异步调用不会生效
*
* 这里通过返回Future<T>来返回异步调用的结果,实现异步回调
*/
@Async
public Future<String> test1() throws InterruptedException {
System.out.println("test1 begin");
long begin = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
System.out.println("test1 end " + (System.currentTimeMillis() - begin));
return new AsyncResult<String>("test1 is done!");
}
@Async
public Future<String> test2() throws InterruptedException {
System.out.println("test2 begin");
long begin = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
System.out.println("test2 end " + (System.currentTimeMillis() - begin));
return new AsyncResult<String>("test2 is done!");
}
@Async
public Future<String> test3() throws InterruptedException {
System.out.println("test3 begin");
long begin = System.currentTimeMillis();
Thread.sleep(random.nextInt(10000));
System.out.println("test3 end " + (System.currentTimeMillis() - begin));
return new AsyncResult<String>("test3 is done!");
}
}