场景:定时器采用同步方法的话,一旦远程调用接口阻塞,界面就会卡主,影响用户使用。
同步与异步的好坏处:
1、同步方法会卡界面,因为UI线程忙于计算;异步多线程方法不卡界面,主线程闲置,计算任务交个子线程去做;
2、同步方法慢,只有一个线程计算;异步多线程方法快,多线程并发计算(多线程的资源消耗更多,线程并不是越多越好);
3、异步多线程是无序的:启动无序,执行时间不确定,结束无序,所以我们不要试图通过启动顺序或是时间等待来控制流程。
SpringBoot通过注解实现异步调用
1、开启异步配置。在类的申明前使用@EnableAsync注解开启异步调用功能
2、编写异步任务方法,使用@Async注解,即可在执行注解方法时自动由Spring框架执行异步操作
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @author: Pagegle
* @date: 2020/7/16 13:46
* @content:
*/
@Component
@Configurable
@EnableScheduling
@EnableAsync
public class Timer {
private TaskExecutor taskExecutor;
public Timer(TaskExecutor taskExecutor){
this.taskExecutor=taskExecutor;
}
@Scheduled(fixedDelay = 60*1000)//
@Async
public void stCache(){
SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ssss");
//异步线程
System.err.println("异步线程"+dateFormat.format(new Date()));
taskExecutor.execute(new Runnable() {
@Override
public void run() {
System.err.println("=1="+dateFormat.format(new Date()));
}
});
taskExecutor.execute(new Runnable() {
@Override
public void run() {
System.err.println("=2="+dateFormat.format(new Date()));
}
});
}
}