测试是否是线程安全
@RequestMapping("/test")
@RestController
public class TestController {
//1、定义num,判断不同线程访问的时候,num的返回结果是否一致
private Integer num=0;
/**
* 2、定义两个方法
*/
@GetMapping("/count1")
public Integer test1(){
System.out.println(++num);
return num;
}
@GetMapping("/count2")
public Integer test2(){
System.out.println(++num);
return num;
}
}
输出结果:

在两次请求中,变量实现了共享,所以是线程不安全的
如何变为线程安全方式
方式一:使用多例模式@Scope("prototype")
@RequestMapping("/test")
@Scope("prototype")
@RestController
方式二:使用threadLocal
@RequestMapping("/test")
@RestController
public class TestController {
//1、定义threadLocal 线程独享
ThreadLocal<Integer> threadLocal=new ThreadLocal<>();
/**
* 2、定义两个方法
*/
@GetMapping("/count1")
public void test1(){
threadLocal.set(1);
System.out.println(threadLocal.get());
}
@GetMapping("/count2")
public void test2(){
threadLocal.set(2);
System.out.println(threadLocal.get());
}
}












![[数据集][目标检测]骑电动车摩托车不戴头盔数据集VOC格式1385张](https://i1.hdslb.com/bfs/archive/1b98ce6a0729dcac5bb74808fe3b79bf1eefb054.jpg@100w_100h_1c.png@57w_57h_1c.png)





