測試是否是線程安全
@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());}}