一、简单实现
启动一个新的线程来运行
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
// 此处编写异步运行代码
}
});
thread.start();
二、注解实现
1.先写一个异步配置类
@Configuration //表明该类是一个配置类
@EnableAsync //开启异步事件的支持
public class AsyncConfig {
//此处成员变量应该使用@Value从配置中读取
private int corePoolSize = 10; // 配置线程池中的核心线程数
private int maxPoolSize = 200; // 配置最大线程数
private int queueCapacity = 10; // 配置队列大小
@Bean
public Executor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(corePoolSize);
executor.setMaxPoolSize(maxPoolSize);
executor.setQueueCapacity(queueCapacity);
executor.initialize();
return executor;
}
}
2.在需要异步运行的方法或者类加上 @Async 注解
@Async
public class asyncTestClass{
public void asyncTest() {
System.out.println("Execute method with configured executor - "
+ Thread.currentThread().getName());
}
}
@Async
public void asyncTest() {
System.out.println("Execute method with configured executor - "
+ Thread.currentThread().getName());
}
调用被 @Async 标记的方法的调用者不能和被调用的方法在同一类中不然不会起作用。