Spring的bean是否线程安全 ╰+攻爆jí腚メ 2024-04-19 11:40 11阅读 0赞 Spring的bean默认scope属性为singleTon,即单例的,有线程安全问题 如果设置@Scope(“prototype”),则每次都会创建新对象,不存在线程安全问题 public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MainConfig.class); Count count = context.getBean("count", Count.class); for(int i=0;i<10000;i++){ Thread t = new Thread(()->{ count.add();//让成员变量count++ }); t.start(); } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(count.count);//预期值10000,有count值小于10000的情况 } 如何实现线程安全 1.同步代码块/同步方法 2.ThreadLocal,提供了线程的局部变量,实现线程的数据隔离
还没有评论,来说两句吧...