一.异步注解 @Async
注意点
1.启用该注解时需要在配置类或者启动类中添加 @EnableAsync
2.@Async 不能在同一个类中,应该新建立一个组件类
3.注解打在方法上作用域为该方法、打在类上时作用域为该类下所有的方法
@Component
@Async
public class AsyncDemo {
public void sendMsg(String msg) throws InterruptedException {
Thread.sleep(10000);
System.out.println("发送消息:"+msg);
}
public void sendMsg2(String msg) throws InterruptedException {
Thread.sleep(5000);
System.out.println("发送消息2:"+msg);
}
}
// 测试类
@RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
@EnableAsync
public class MyTest {
@Test
public void testaaa() throws InterruptedException {
asyncDemo.sendMsg("我是消息1");
asyncDemo.sendMsg2("我是消息2");
System.out.println("执行了....");
Thread.sleep(20000);
System.out.println("我是主线程执行完毕");
}
}
执行结果 证明先执行了主方法中的输出语句 然后在执行异步中的方法
执行了....
发送消息2:我是消息2
发送消息:我是消息1
我是主线程执行完毕