- 异步方法
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Component;
/**
* @Author: HYZ
* @CreateDate: 2020/1/16 21:54
* @Describe: 异步方法
* @Version: 1.0
**/
@Slf4j
@Component
@EnableAsync
public class SyncOpera {
@Async
public void operation() throws InterruptedException {
for(int i = 0; i < 10; i++) {
Thread.sleep(1000);
log.info(String.format("方法:%s 第:%s, 其他信息%s",Thread.currentThread().getStackTrace()[1].getMethodName(),Thread.currentThread().getStackTrace()[1].getLineNumber(),"异步操作"));
}
}
}
类加上@EnableAsync
方法使用 @Async
- 测试
package com.vivo.xyz.hyz202001;
import com.vivo.xyz.hyz202001.service.SyncService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* @Author: HYZ
* @CreateDate: 2020/1/16 22:15
* @Describe:
* @Version: 1.0
**/
@SpringBootTest
@RunWith(SpringJUnit4ClassRunner.class)
public class SyncServiceTest {
@Autowired
SyncService syncService ;
@Test
public void SyncOperationTest() throws InterruptedException{
syncService.SyncOperation();
}
}
结果:方法异步执行