spring整合多线程---@Async注解
-
基本配置
-
启动添加注解
-
@SpringBootApplication
@EnableAsync
public class Demo000Application {
public static void main(String[] args) {
SpringApplication.run(Demo000Application.class, args);
}
} -
方法上添加注解
-
@Component
public class test01 {
@Async
public void log(){
Log log = LogFactory.getLog("log");
log.info("ok");
}
}
-
手写@Async异步注解
-
controller调用异步方法
-
@RestController
@RequestMapping("/test")
public class Test02 {
@RequestMapping("/async")
public void asyncLog(){
//异步方法
Test01.log();
System.out.println("----------test--------");
}
}
-
-
定义异步方法
-
@Component
public class Test01 {
//使用自定义注解
@AwAsync("myExecutor")
public static void log(){
System.out.println("-----write log-----");
}
}
-
-
捕捉自定义注解@AwAsync,异步执行
-
@Component
@Aspect
public class AopAnnotation {
//注入自定义线程池
@Autowired
MyExecutor executor;
@Pointcut(value = "@annotation(com.example.demo_000.demo.Controller.My*)")
public void myPointCut(){}
@Around("myPointCut()")
public void log(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
//线程池异步执行目标方法
executor.execute(() -> {
try {
proceedingJoinPoint.proceed();
} catch (Throwable e) {
throw new RuntimeException(e);
}
});
}
} -
补充--自定义线程池
-
@Component
public class MyExecutor {
ArrayList<Runnable> threads;
LinkedBlockingDeque<Runnable> tasks;
public MyExecutor() {
threads= new ArrayList<>();
tasks= new LinkedBlockingDeque<>();
for (int i = 0; i < 2; i++) {
Thread thread = new Thread(() -> {
while (true) {
Runnable poll = tasks.poll();
if (poll != null) {
poll.run();
}
}
});
thread.start();
threads.add(thread);
}
}
public boolean execute(Runnable runnable){
return tasks.offer(runnable);
}
}
-
-