Java 异步执行方法
一.利用多线程
直接new线程
Thread t = new Thread(){
@Override
public void run() {
longTimeMethod();
}
};
使用线程池
private ExecutorService executor = Executors.newCachedThreadPool() ;
public void fun() throws Exception {
executor.submit(new Runnable(){
@override
public void run() {
try {
//要执行的业务代码,我们这里没有写方法,可以让线程休息几秒进行测试
Thread.sleep(10000);
System.out.print("睡够啦~");
}catch(Exception e) {
throw new RuntimeException("报错啦!!");
}
}
});
}
二.采用Spring 的异步方法去执行(无返回值)
在启动类或者配置类加上 @EnableAsync 注解.
package me.deweixu.aysncdemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
@EnableAsync
@SpringBootApplication
public class AysncDemoApplication {
public static void main(String[] args) {
SpringApplication.run(AysncDemoApplication.class, args);
}
}
先把longTimeMethod 封装到Spring的异步方法中,这个方法一定要写在Spring管理的类中,注意注解@Async
@Async注解可以用在方法上,也可以用在类上,用在类上,对类里面所有方法起作用
@Service
public class AsynchronousService{
@Async
public void springAsynchronousMethod(){
longTimeMethod();
}
}
其他类调用这个方法。这里注意,一定要其他的类,如果在同类中调用,是不生效的。具体原因,可以去学习一下Spring AOP的原理
@Autowired
private AsynchronousService asynchronousService;
public void useAsynchronousMethod(){
//我们需要执行的代码1
asynchronousService.springAsynchronousMethod();
//我们需要执行的代码2
}
三.采用Spring 的异步方法+Future接收返回值
先把longTimeMethod 封装到Spring的异步方法中,这个异步方法的返回值是Future的实例。这个方法一定要写在Spring管理的类中,注意注解@Async。
@Service
public class AsynchronousService{
@Async
public Future springAsynchronousMethod(){
Integer result = longTimeMethod();
return new AsyncResult(result);
}
}
其他类调用这个方法。这里注意,一定要其他的类,如果在同类中调用,是不生效的。
如果调用之后接收返回值,不对返回值进行操作则为异步操作,进行操作则转为同步操作,等待对返回值操作完之后,才会继续执行主进程下面的流程
@Autowired
private AsynchronousService asynchronousService;
public void useAsynchronousMethod(){
Future future = asynchronousService.springAsynchronousMethod();
future.get(1000, TimeUnit.MILLISECONDS);
}
四.原生Future方法
我们需要执行的代码1
Future future = longTimeMethod2();
我们需要执行的代码2
Integer result = future.get();
可以看到,我们调用longTimeMethod2返回一个Future对象(注意了,这里的longTimeMethod2当然不是上面的longTimeMethod),然后处理“我们需要执行的代码2”,到了需要返回结果的时候直接调用future.get()便能获取到返回值。下面我们来看看longTimeMethod2如何实现。
private Future longTimeMethod2() {
//创建线程池
ExecutorService threadPool = Executors.newCachedThreadPool();
//获取异步Future对象
Future future = threadPool.submit(new Callable() {
@Override
public Integer call() throwsException {
return longTimeMethod();
}
});
return future;
}
上一篇: java 异步调用返回
下一篇: 了解 Java 异步编程
推荐阅读
-
在 ts 中实现类 java hashmap 的简单方法
-
Java 基础知识:面向对象编程 3-2 Java 本地方法
-
Java Stream API flatMap 方法
-
java.io.StreamCorruptedException: invalid stream header of reasons及解决方法
-
IDEA 编译错误 "java: constant string is too long "的解决方法--二、问题的原因
-
JavaEE 初级] 深入理解线程池的概念以及 Java 标准库提供的方法参数分析
-
Java 混淆的几种方法
-
解决如何在 Idea 中断点调试 Java Agent 的完美方法 - 前言
-
在 SpringBoot-MybatisPlus 项目中,在控制台中查看 sql 执行日志的方法
-
JAVA 并发编程系列 (13) Future、FutureTask 异步小王子