Spring task @Async執行失敗原因分析

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}//異步返回結果

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章