//region 异步线程查询测试
@Test
void testThread() {
CountThread countThread = new CountThread();
Thread thread = new Thread(countThread);
thread.setName("线程1");
thread.start();
long millis1 = System.currentTimeMillis();
for (int i = 0; i < 10; i++) {
int countSCP = testMapper.countSCP();
System.out.println(countSCP);
}
long millis2 = System.currentTimeMillis();
long useTime = millis2 - millis1;
System.out.println(useTime);
Thread thread2 = new Thread(countThread);
thread2.setName("线程2");
thread2.start();
new Thread(() -> {
try {
System.out.println("开始休眠进程");
Thread.sleep(5000);
}catch (Exception e) {
e.printStackTrace();
}finally {
System.out.println("结束休眠进程");
}
},"线程3").start();
connectOpenCV();
Mat img = Imgcodecs.imread("src/main/resources/img/123.jpg");
Imgproc.resize(img,img,new Size(),0.5,0.5);
HighGui.imshow("img",img);
HighGui.waitKey();
img.release();
closeOpenCV();
}
//endregion
/**
* 查询时需要配置两个配置类
* 一个是 @Configuration配置类加新注解 @EnableAsync
* 一个是直接移植新的 BeanContext配置类,用于防止 Mapper空指针的情况
*/
@Service
class CountThread implements Runnable{
@Autowired
private TestMapper testMapper;
@Async
public void test(){
testMapper = BeanContext.getBean(TestMapper.class);
long m1 = System.currentTimeMillis();
String threadName = Thread.currentThread().getName();
System.out.println(threadName + " 开始时间: " + m1);
int countSCP = testMapper.countSCP();
for (int i = 0; i < 5; i++) {
System.out.println(threadName + " : " + countSCP);
}
long m2 = System.currentTimeMillis();
System.out.println(threadName + " 结束时间: " + m2);
System.out.println(m2 - m1);
}
@Override
public void run() {
test();
}
}
BeanContext配置类
/**
* 手动获取Bean
* https://blog.csdn.net/tiger0709/article/details/78270768
* https://blog.csdn.net/u011493599/article/details/78522315
*/
@Component
public class BeanContext implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
BeanContext.applicationContext = applicationContext;
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
@SuppressWarnings("unchecked")
public static <T> T getBean(String name) throws BeansException {
return (T) applicationContext.getBean(name);
}
public static <T> T getBean(Class<T> clz) throws BeansException {
return (T) applicationContext.getBean(clz);
}
}