题目描述在学习多线程的知识,下面的代码跑出的结果与预想的不一致,看不明白问题出在哪里,麻烦大家帮忙看看题目来源及自己的思路我想的是程序结束后staticv的值是个整数200000,但是每次结果都在19xxxxxxx,离的很近,又不像同步出了问题,不知是哪里出了问题,另外代码注释标注为#的位置,foo被synchronized标志,那同步的是SyncObj的实例对象而不是SyncObjc.class,明明是两个实例对象在被调用没有加同步,我以为volatile没加上去结果是错误的,但执行的结果好像没区别,为什么?我不清楚我的理解哪里出了问题,请大家多多指教,谢谢。相关代码packageconcurrency;importjava.util.concurrent.CountDownLatch;importjava.util.concurrent.ExecutorService;importjava.util.concurrent.Executors;importjava.util.concurrent.TimeUnit;publicclassSynchronizedTest{publicstaticvoidmain(String[]args)throwsInterruptedException{ExecutorServiceexecutor=Executors.newCachedThreadPool();SyncObjobj1=newSyncObj();SyncObjobj2=newSyncObj();CountDownLatchcountDownLatch=newCountDownLatch(20);for(inti=0;i<10;i++){executor.execute(newTT(obj1,countDownLatch));executor.execute(newTT(obj2,countDownLatch));}countDownLatch.await();System.out.println("result----------------------"+SyncObj.staticv);}}classSyncObj{publicstaticvolatileintstaticv=0;//######volatile是不是可有可无?publicsynchronizedvoidfoo(){for(inti=0;i<1000;i++){System.out.println(staticv);staticv++;}}}classTTimplementsRunnable{publicCountDownLatchcountDownLatch;publicSyncObjobj;publicTT(SyncObjobj,CountDownLatchcountDownLatch){this.obj=obj;this.countDownLatch=countDownLatch;}@Overridepublicvoidrun(){for(inti=0;i<100;i++){obj.foo();}countDownLatch.countDown();}}
猛跑小猪
相关分类