Spring task @Async执行失败原因分析
来源:互联网 发布:盗贼源码解压密码 编辑:程序博客网 时间:2024/06/05 05:00
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执行失败原因分析
- 自动化脚本执行失败原因分析
- Android之Async Task异步任务分析
- Android Lint task执行失败
- Spring @Async不执行问题
- spring @Async 注解异步执行
- Spring Boot Async异步执行
- crontab 执行失败原因
- 项目失败原因分析
- 占座网失败原因分析
- 装机失败原因分析
- Spring task 执行两次解决方法
- crontab脚本执行失败原因
- Task的执行过程分析
- 解决lint task执行失败问题
- 使用spring的@Async异步执行方法
- Spring异步执行(@Async)2点注意事项
- 使用spring的@Async异步执行方法
- selenium调用chrome
- git工作流
- C++实现停车场管理系统
- 常用Android开发组件之列表类组件
- C++ primer 学习笔记(第二章:变量和基本类型)
- Spring task @Async执行失败原因分析
- 设计模式之单例模式的7种写法
- iOS 在cell上面设置登陆账号密码
- jsp:include 导入一个action
- MySQL查询优化
- Android四大组件之Activity--启动模式
- 微信摇一摇功能
- 多线程初探(三)
- 自制简单发邮件jar包