springboot异步方法

541 阅读1分钟

同步方法

1.创建一个service

@Component
public class AsyncService {

public void test1(){
//打印线程name
System.out.println("test1 start:" + Thread.currentThread().getName());
//模拟程序执行
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("test1 end");
}

public void test2(){
System.out.println("test2 start:" + Thread.currentThread().getName());
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("test2 end");
}

public void test3(){
System.out.println("test3 start:" + Thread.currentThread().getName());
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("test3 end");
}
}

2.测试

@RunWith(SpringRunner.class)
@SpringBootTest
public class AsyncApplicationTests {
@Autowired
private AsyncService asyncService;

@Test
public void testAsync() {
asyncService.test1();
asyncService.test2();
asyncService.test3();
}

}

控制台打印:
test1 start:main
test1 end
test2 start:main
test2 end
test3 start:main
test3 end

异步方法

1.开启异步方法

@SpringBootApplication
//开启异步方法
@EnableAsync
public class AsyncApplication {

public static void main(String[] args) {
SpringApplication.run(AsyncApplication.class, args);
}

}

2.设置线程池(非必须)

@Configuration
public class BeanLoad {

@Bean
public ThreadPoolTaskExecutor threadPoolTaskExecutor(){
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setThreadNamePrefix("springboot-");
executor.setCorePoolSize(3);
executor.setMaxPoolSize(10);

executor.initialize();
return executor;
}
}

3.创建异步方法

@Component
public class AsyncService {

//@Async表示方法是一个异步方法
@Async
public void test1(){
//和同步方法一样
}

@Async
public void test2(){
//和同步方法一样
}

@Async
public void test3(){
//和同步方法一样
}
}

4.测试

@RunWith(SpringRunner.class)
@SpringBootTest
public class AsyncApplicationTests {
@Autowired
private AsyncService asyncService;

@Test
public void testAsync() {
asyncService.test1();
asyncService.test2();
asyncService.test3();
//避免主线程结束出现错误
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

}

控制台打印:
test3 start:springboot-3
test2 start:springboot-2
test1 start:springboot-1
test2 end
test3 end
test1 end

每次打印的结果顺序都可能不一样

项目路径


作者博客

作者公众号 在这里插入图片描述