同步方法
- 創(chuàng)建一個service
@Component
public class AsyncService {
public void test1(){
//打印線程name
System.out.println("test1 start:" + Thread.currentThread().getName());
//模擬程序執(zhí)行
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");
}
}
- 測試
@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
異步方法
- 開啟異步方法
@SpringBootApplication
//開啟異步方法
@EnableAsync
public class AsyncApplication {
public static void main(String[] args) {
SpringApplication.run(AsyncApplication.class, args);
}
}
- 設(shè)置線程池(非必須)
@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;
}
}
- 創(chuàng)建異步方法
@Component
public class AsyncService {
//@Async表示方法是一個異步方法
@Async
public void test1(){
//和同步方法一樣
}
@Async
public void test2(){
//和同步方法一樣
}
@Async
public void test3(){
//和同步方法一樣
}
}
- 測試
@RunWith(SpringRunner.class)
@SpringBootTest
public class AsyncApplicationTests {
@Autowired
private AsyncService asyncService;
@Test
public void testAsync() {
asyncService.test1();
asyncService.test2();
asyncService.test3();
//避免主線程結(jié)束出現(xiàn)錯誤
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
每次打印的結(jié)果順序都可能不一樣
作者公眾號