Spring的bean是否線程安全

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,提供了線程的局部變量,實現線程的數據隔離

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章