0
点赞
收藏
分享

微信扫一扫

Java Bean线程问题

卿卿如梦 2022-03-11 阅读 53
javaspring

源码

1.controller类

@RestController
//@Scope(value = "prototype")
public class SpringBeanController {

    @RequestMapping("say")
    public String sayHello(){
        return "Hello Spring Boot";
    }

    private int var = 0; // 定义一个普通变量

    private static int staticVar = 0; // 定义一个静态变量

    @Value("${test-int}")
    private int testInt; // 从配置文件中读取变量

    ThreadLocal<Integer> tl = new ThreadLocal<>(); // 用ThreadLocal来封装变量

    @Autowired
    SpringBeanService user;


    @GetMapping(value = "/test_var")
    public String test() {
        tl.set(1);
        System.out.println("先取一下user对象中的值:"+user.getAge()+"===再取一下hashCode:"+user.hashCode());
        int age = user.getAge();
        user.setAge(++age);
        System.out.println("普通变量var:" + (++var) + "===静态变量staticVar:" + (++staticVar) + "===配置变量testInt:" + (++testInt)
                + "===ThreadLocal变量tl:" + tl.get()+"===注入变量user:" + user.getAge());
        return "普通变量var:" + var + ",  静态变量staticVar:" + staticVar + ",  配置读取变量testInt:" + testInt + ",  ThreadLocal变量tl:"
                + tl.get() + "  注入变量user:" + user.getAge();
    }

    @GetMapping(value = "/test_var2")
    public void test2() {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        RequestContextHolder.setRequestAttributes(servletRequestAttributes,true);//设置子线程共享
        for (int i = 0; i < 5; i++) {
           new Thread("I am thread"+i){

              @Override
              public void run() {
                  tl.set(1);
                  System.out.println("先取一下user对象中的值:"+user.getAge()+"===再取一下hashCode:"+user.hashCode());
                  int age = user.getAge();
                  user.setAge(++age);
                  System.out.println("************");
                  System.out.println("普通变量var:" + (++var) + "===静态变量staticVar:" + (++staticVar) + "===配置变量testInt:" + (++testInt)
                         + "===ThreadLocal变量tl:" + tl.get()+"===注入变量user:" + user.getAge());
              }
          }.start();
        }
    }
}

2.service类

@Service
//@Scope(value = "request", proxyMode= ScopedProxyMode.TARGET_CLASS)
//@Scope(value = "prototype")
public class SpringBeanService {

    public int age;

    public void setAge(int age) {
        this.age = age;
    }

    public int getAge() {
        return age;
    }
}

测试结果(发起三次http请求)

  1. 将controller设置为单例,service设置为单例
    在这里插入图片描述

  2. 将controller设置为@Scope(value = “prototype”),service设置为单例
    在这里插入图片描述

  3. 将controller设置为@Scope(value = “prototype”),service设置为@Scope(value = “prototype”)
    在这里插入图片描述

  4. 将controller设置为单例,service设置为@Scope(value = “prototype”)
    在这里插入图片描述

  5. 将controller设置为单例,service设置为@Scope(value = “request”, proxyMode= ScopedProxyMode.TARGET_CLASS)
    在这里插入图片描述

Spring Bean的线程安全
Spring 中的bean 是线程安全的吗?

举报

相关推荐

0 条评论