首頁  >  問答  >  主體

并发 - Java static / non-static synchronized方法同时修改static成员变量,会有问题吗?

阿神阿神2763 天前536

全部回覆(1)我來回復

  • 迷茫

    迷茫2017-04-18 10:39:15

    參考StackOverflow問題:

    http://stackoverflow.com/ques...

    但是,還是意猶未盡,還請各位多多指教、探討!


    補充:

    運行以下測試程序,最後的結果並不是20000,中間有很多次結果都被覆蓋了。

    public class Test {
        
        private static int staticVariableOne = 0;
    
        public Test() {
            super();
        }
        
        public static int getStaticVariableOne() {
            return staticVariableOne;
        }
    
        public static void setStaticVariableOne(int staticVariableOne) {
            Test.staticVariableOne = staticVariableOne;
        }
        
        private static void increaseStaticVariableOne() {
            staticVariableOne++;
        }
        
        public synchronized void add() {
            System.out.println("执行 add() 开始...");
            try {
                for (int i  = 0; i < 10000; i++) {
                    increaseStaticVariableOne();
                    Thread.sleep(1);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("执行 add() 完毕...");
        }
     
        public synchronized static void addStatic() {
            System.out.println("执行 addStatic() 开始...");
            try {
                for (int i  = 0; i < 10000; i++) {
                    increaseStaticVariableOne();
                    Thread.sleep(2);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("执行 addStatic() 完毕...");
        }
    
    }
    public class StudyMain {
        public static void main( String[] args ) {
            
            final Test insertData = new Test();
            Thread threadOne = new Thread() {
                @Override
                public void run() {
                    insertData.add();
                }
            };
            
            Thread threadTwo = new Thread() {
                @Override
                public void run() {
                    Test.addStatic();
                }
            };
            
            threadOne.start();
            threadTwo.start();
            try {
                threadOne.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            try {
                threadTwo.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("After 20000 times increasements, final staticVariableOne is "
            + Test.getStaticVariableOne());
        }
    }

    回覆
    0
  • 取消回覆