扫码关注官方订阅号
闭关修行中......
参考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()); } }
微信扫码关注PHP中文网服务号
QQ扫码加入技术交流群
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
PHP学习
技术支持
返回顶部
参考StackOverflow问题:
http://stackoverflow.com/ques...
但是,还是意犹未尽,还请各位多多指教、探讨!
补充:
运行如下测试程序,最后的结果并不是20000,中间有很多次结果都被覆盖了。