一、异步的八种实现方式
1、线程Thread
2、Future
3、异步框架CompletableFuture
4、Spring注解@Async
5、Spring ApplicationEvent事件
6、消息队列
7、第三方异步框架,比如Hutool的ThreadUtil
8、Guava异步
二、什么是异步
首先先看一个常见的用户下单的场景:
什么是异步?
在同步操作中,执行到发送短信的时候,我们必须等待这个方法彻底执行完才能执行赠送积分这个操作,如果赠送积分这个动作执行时间较长,发送短信需要等待,这就是典型的同步场景。
实际上,发送短信和赠送积分没用任何的依赖关系,通过异步,我们可以实现赠送积分和发送短信这两个操作能够同时进行,比如:
这就是异步,是不是非常简单,下面就说说异步的几种实现方式吧。
三、异步编程
1、线程异步
public class AsyncThread extends Thread {
@Override
public void run(){
System.out.println("Current thread name:" + Thread.currentThread().getName()+"send
email success!");
}
public static void main(String[] args){
AsyncThread asyncThread=new AsyncThread();
asyncThread.run();
}
}
当然如果每次都创建一个Thread线程,频繁的创建、销毁,浪费系统资源,我们可以采用线程池:
private ExecutorService executorService = Executors.newCachedThreadPool();
public void fun(){
excutorService.submit(new Runnanle(){
@Override
public void run() {
log.info("执行业务逻辑...");
}
});
}
可以将业务逻辑封装到Runnable或Callable中,交由线程池来执行。
2、Future异步
@Slf4j
public class FutureManager {
public String execute() throws Exception {
ExecutorService executor = Executors.newFixedThreadPool(1);
Future<String> future = executor.submit(new Callable<String>(){
@Override
public String call() throws Exception {
System.out.println("--- task start ---");
Thread.sleep(3000);
System.out.println("--- task finish ---");
}
});
//这里需要返回值