84669 person learning
152542 person learning
20005 person learning
5487 person learning
7821 person learning
359900 person learning
3350 person learning
180660 person learning
48569 person learning
18603 person learning
40936 person learning
1549 person learning
1183 person learning
32909 person learning
闭关修行中......
Reference StackOverflow question:
http://stackoverflow.com/ques...
However, I still have more to say, so please give me your advice and discussion!
Run the following test program, the final result is not 20000, the results are overwritten many times in the middle.
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()); } }
Reference StackOverflow question:
http://stackoverflow.com/ques...
However, I still have more to say, so please give me your advice and discussion!
Added:
Run the following test program, the final result is not 20000, the results are overwritten many times in the middle.