您的位置:首页 > 编程语言 > Java开发

Spring task @Async执行失败原因分析

2016-01-19 11:00 495 查看
package cn.yang.test.utils;

import cn.yang.test.entity.Student;

import org.springframework.scheduling.annotation.*;

import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;

import java.util.Date;

import java.util.concurrent.Future;

/**

* Created by admin on 2016/1/18.

*/

@Component

public class ScheduledTasks {

@Scheduled(fixedRate = 3000)

public void run() {

System.out.println(new SimpleDateFormat(“yyyy-MM-dd:hh:mm:ss” +

“”).format(new Date()));

}

这个是异步执行的代码

@Async

public Future run2(int i){

try {

System.out.println(“async—”);

Thread.sleep(i);

} catch (InterruptedException e) {
e.printStackTrace();
}

Student stu=new Student();
stu.setName("yang");
stu.setAge(20);
return new AsyncResult<Student>(stu);
}


}

测试异步执行

@Autowired

private ScheduledTasks scheduledTasks;

public void test1() throws ExecutionException, InterruptedException {

System.out.println(“Asy start!”);

//Future<Student> stringFuture = new ScheduledTasks().run2(20000);


上面注释的部分就是之前错误的写法,重新new 了一个ScheduledTasks对象,new出的对象不归spring管理,所以调用上面@Async标注的异步方法并没有异步返回结果。

应该注入spring管理的scheduledTasks对象,这样调用的时候方法才会产生异步返回的结果

Future<Student> stringFuture =scheduledTasks.run2(20000);
System.out.println("Asy back!");
int i=0;
while (!stringFuture.isDone()){
Thread.sleep(1000);
System.out.println(i++);

}

System.out.println(stringFuture.get().toString());
}


测试结果

Asy start!

Asy back!

async—

0

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

Student{name=’yang’, age=20}//异步返回结果
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  spring 异步 task Async